Spring IoC容器(四)容器、环境配置及附加功能

news2024/9/24 15:27:39

 本文内容包括容器的@Bean 及 @Configuration 注解的使用、容器环境的配置文件及容器的附加功能(包括国际化消息、事件发布与监听)。

1 容器配置

在注解模式下,@Configuration 是容器核心的注解之一,可以在其注解的类中通过@Bean作用于方法上来配置Bean。xml 与 注解模式可以混合在一起使用。

1.1 @Bean

作用类似于xml 配置文件中的<bean/>标签。可以在注解内标识bean名,也可定义一些列别名。

作用对象

@Component作用于类,@Bean作用于方法。

实现原理

@Component 通常通过类路径扫描来自动探测,自动装配到Spring容器中,而@Bean则是在标有该注解的方法中创建这个Bean。

自定义性

@Bean 的自定义性更强。例如引入第三方库中的类需要装配到Spring时,只能使用@Bean来实现。

表 @Bean 与 @Component的对比

通常是在@Configuration注解的类中来使用@Bean,这种被称为“Full模式”,相反,如果没在@Configuration注解的类中使用@Bean,则被称为“Lite模式”。

1.1.1 Lite 模式

lite 模式定义如下:

1)在非@Configuration标记(例如@Component或者没有任何Spring注解,但在该类中的某个方法上使用了@Bean)的类里定义的@Bean方法。

2)@Configuration(proxyBeanMethods=false)标记的类内定义的@Bean方法。

该模式相对于Full模式有以下限制:

  1. 不会被CGLIB代理,而是使用了原始的类类型。
  2. 该类的@Bean方法相互之间不能直接调用(如果直接调用会生成新的实例)。
//@Configuration(proxyBeanMethods = false)
public class LiteConfiguration {
    @Bean
    public Service liteService1() {
        System.out.println("liteService1 实例化");
        return new Service(){};
    }

    @Bean
    public Service liteService2() {
        System.out.println("liteService2 实例化" + liteService1());
        return new Service(){};
    }
}

public class LiteTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(FullConfiguration.class,LiteConfiguration.class);
        Object fullService1 = applicationContext.getBean("full1");
        Object liteService1 = applicationContext.getBean("liteService1");
        System.out.println(fullService1);
        System.out.println(liteService1);
    }
}

图 Lite模式下,bean没有被代理

通常情况下,推荐使用Full模式。Lite模式可能更时候需要更快响应速度或资源受限时。

1.2 @Configuration

作用类似于xml配置文件中的<beans/>标签。可以在类里配置bean,及可以在类上配置bean的扫描路径。在同一个@Configuration注解的类中,@Bean标注的方法可以相互调用,且无论调用多少次,都只会生成一个单例bean(该bean的作用域要为单例)。

@Configuration
public class FullConfiguration {
    // 如果定义了别名,则默认名失效
    @Bean({"full1","full"})
    public Service fullService1() {
        System.out.println("fullService1 实例化");
        return new Service() {};
    }

    @Bean
    public Service fullService2() {
        // 直接调用了fullService1()方法,无论该方法在个类被调用多少次,都只会生成一个实例(单例)
        System.out.println("fullService2 实例化:" + fullService1());
        return new Service() {};
    }

    @Bean
    public Service fullService3() {
        // 这里直接调用了fullService1()方法
        System.out.println("fullService3 实例化:" + fullService1());
        return new Service() {};
    }
}

1.2.1 @Lookup 方法注入依赖 Look Method Injection

通过@Inject注入时,依赖只会被注入一次,即在该bean被初始化时。如果想实现每次都能获取一个新的bean,可以使用@Lookup注解。如果想动态获取一个被容器管理的Bean实例时很有用。

该注解核心思想时:使用抽象方法声明需要注入的Bean,Spring在运行时动态生成其子类并重新实现该抽象方法(cglib代理),从而实现原型Bean的注入。使用规则如下:

  1. 可以在@Lookup注解中指定bean的名字。
  2. 该方法要符合cglib 代理方法的规则(不能是private、static、final)。
  3. 如果想每次调用都生成新的bean,则对应的bean作用域不能为singleton。(适合生命周期较短的Bean)
@Component
@Scope(value = "prototype")
public class LookupService1 implements Service {
}

@Component
public class LookupService2 implements Service {
}

@Component
public class LookupManage {
    @Lookup("lookupService1")
    public Service lookupService() {
        return null;
    }
}

@Configuration
@ComponentScan(basePackages = "lookup")
public class LookupConfiguration {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(LookupConfiguration.class);
        LookupService1 lookupService1 = context.getBean(LookupService1.class);
        LookupService2 lookupService2 = context.getBean(LookupService2.class);
        System.out.println("原型 lookupService1:" + lookupService1);
        System.out.println("原型 lookupService2:" + lookupService2);
        System.out.println("--------lookup---------");
        LookupManage lookupManage = context.getBean(LookupManage.class);
        System.out.println(lookupManage.lookupService());
        System.out.println(lookupManage.lookupService());
    }
}

1.2.2 @Import 依赖导入

可以在类上使用@Import注解来导入其他@Configuration注解的类,这些被导入的类与该类就组合成了一个整体(类之间的Bean可以相互依赖)。

@Configuration
public class Configuration1 {
    @Bean
    public Service1 service1(Service2 service2) {
        System.out.println("service1() service2:");
        Service1 service1 = new Service1();
        System.out.println("service1:" + service1);
        return service1;
    }
}

@Configuration
public class Configuration2 {
    @Bean
    public Service2 service2(Service3 service3) {
        System.out.println("service2() service3:" + service3);
        Service2 service2 = new Service2();
        System.out.println("service2:" + service2);
        return service2;
    }
}

@Configuration
@Import({Configuration1.class,Configuration2.class})
public class Configuration3 {
    @Bean
    public Service3 service3() {
        Service3 service3 = new Service3();
        System.out.println("service3:" + service3);
        return service3;
    }

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Configuration3.class);
        Service3 service3 = context.getBean(Service3.class);
        Service2 service2 = context.getBean(Service2.class);
        Service1 service1 = context.getBean(Service1.class);
        System.out.println("service1:" + service1);
        System.out.println("service2:" + service2);
        System.out.println("service3:" + service3);
    }
}

1.3 AnnotationConfigApplicationContext

用于创建和初始化基于Java配置类的容器。可以通过构造函数或register方法(参数为class类型,可以是有@Configuration、@Component注解的或者没有任何注解的类)来指定需要注册的bean。容器会将这些类注册为bean。

还可以通过scan方法来指定需要扫描的类路径。

使用了register或scan方法后,要使用其refresh方法来刷新容器。

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(ProfilesConfiguration.class);
context.refresh();
Service bean = context.getBean(Service.class);

1.4 xml 与 注解混合使用

在代码中可以将注解与xml格式的bean配置文件混合在一起使用。可分为两种情况:1) 以XML为中心;2)以注解为中心。

1.4.1 以XML为中心

在代码中,以XML配置为主。需要使用注解形式配置的bean时,有两种方法:1)在xml中 使用 <component-scan/>标签来指定需要扫描的类路径;2)在xml中将@configuration注解的类用<bean/>标签来配置,还必须加上<context:annotation-config/>标签。

<!--xml_center.xml-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--    要让xml支持注解,必须加上这个-->
    <context:annotation-config/>
    <context:component-scan base-package="container.xml"/>
    <bean class="container.xml.XMLConfiguration"/>
    <bean class="container.xml.XMLService">
        <constructor-arg name="service1" ref="service1"/>
        <property name="service2" ref="service2"/>
    </bean>
</beans>

@Configuration
public class XMLConfiguration {

    public XMLConfiguration() {
        System.out.println("XMLConfiguration实例化");
    }
    @Bean
    public Service1 service1() {
        System.out.println("service1 实例化");
        return new Service1();
    }

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("xml_center.xml");
        XMLService xmlService = context.getBean(XMLService.class);
        System.out.println("xmlService:" + xmlService);
        Object service = context.getBean("service1");
        System.out.println("service:" + service);
        System.out.println("service2:" + xmlService.getService2());
    }
}

1.4.2 以注解为中心

在代码中,以注解为主,可以在有@Configuration注解的类上,加上@ImportResource注解,来指定xml配置文件的路径。

@Configuration
@ImportResource("classpath:annotate_center.xml")
public class AnnotateConfiguration {
    @Bean("service1")
    public Service service1(XMLService xmlService) {
        System.out.println("service1 xmlService:" + xmlService);
        return new Service() {};
    }

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AnnotateConfiguration.class);
        XMLService xmlService = context.getBean(XMLService.class);
        Object service1 = context.getBean("service1");
        System.out.println(service1);
        System.out.println("xmlService:" + xmlService);
    }
}

2 环境配置

Environment接口是对容器环境的一个抽象,它包括两个访问:概要文件和属性。

2.1 @Profile 概要文件

@Profile是一种将容器的bean按照不同配置进行分组的机制。用于指示一个或多个组件仅在某些特定的配置下被创建和初始化。

在该注解中可以使用逻辑运算符(与 & 或 | 非 !)。

@Configuration
public class ProfilesConfiguration {

    @Bean
    @Profile("dev & other")
    public Service devService() {
        System.out.println("实例化 devService");
        return new Service() {};
    }

    @Bean
    @Profile("prod")
    public Service prodService() {
        System.out.println("实例化 prodService");
        return new Service() {};
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.getEnvironment().setActiveProfiles("other","dev");
        context.register(ProfilesConfiguration.class);
        context.refresh();
        Service bean = context.getBean(Service.class);
        System.out.println(bean);
    }
}

2.2 property 环境属性

Environment 提供了在多种环境下搜索属性的接口。不同环境属性名相同时优先级如下:1)ServletConfig (例如DispatcherServlet上下文)。2)ServletContext参数(例如web.xml)。3)JNDI环境变量。4)JVM系统变量。5)JVM系统环境。

还可以使用@PropertySource 注解来引入自定义属性。

@Configuration
@PropertySource("/pro.properties")
public class PropertyConfiguration {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(PropertyConfiguration.class);
        String name = context.getEnvironment().getProperty("my.name");
        String address = context.getEnvironment().getProperty("my.address");
        System.out.println(name + ":" + address);
    }
}

pro.properties文件:
my.name=Jon
my.address=China

3 附加功能

ApplicationContext类还实现了MessageSource(消息)、ApplicationEventPublisher(事件发布)等接口。让容器拥有了像事件发布与监听、消息国际化等附加功能。

3.1 MessageSource 消息国际化

要实现这个功能,必须注册一个ResourceBundleMessageSource类型的bean。创建该bean时,可以指定消息的资源包(properties格式的文件)及文件编码等信息。

如果要实现国际化消息,则需要创建对应地域的资源包。

message/exception.properties:
error=The argument {0} is big error

message/message_en.properties:
info=info str 
content=message content

message/message_en.properties:
info=中文内容
content=消息内容

@Configuration
public class MessageSourceConfiguration{
    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setBasenames("message/message","message/exception");
        return messageSource;
    }

    public static void main(String[] args) {
        MessageSource messageSource = new AnnotationConfigApplicationContext(MessageSourceConfiguration.class);
        String info = messageSource.getMessage("info", null, Locale.ENGLISH);
        System.out.println("info:" + info);
        String error = messageSource.getMessage("error", new Object[]{"userName"}, Locale.ENGLISH);
        System.out.println("error:" + error);

        System.out.println(messageSource.getMessage("info", null, Locale.CHINESE));;
    }
}

3.2 事件发布与监听

可以自定义事件,需要继承ApplicationEvent类。使用@EventListener注解作用于方法上,参数为对应的事件类型来实现对该事件的监听,可以通过@EventListener注解的筛选表达式来对监听的事件进行筛选。返回值可以是void,也可以是事件类型,当为事件类型时,表示继续发布返回的事件。

监听事件时默认是同步的,即会阻塞其他监听器。可以使用@Async来使该监听方法成为异步监听,使用异步监听有以下限制;1)异常不会传递到调用者。2)建议(同步或异步都可以通过返回一个事件来继续发布事件)不要用返回值来再次发布事件,而是在方法内部手动发布事件。这是为了让事件代码更清晰及更好控制。

public class CustomEvent1 extends ApplicationEvent {
    public CustomEvent1(Object source) {
        super(source);
    }
}

public class CustomEvent2 extends ApplicationEvent {
    public CustomEvent2(Object source) {
        super(source);
    }
}

@Configuration
public class EventConfiguration {

    @EventListener(condition = "event.source == '测试1'")
    @Order(1)
    @Async
    public CustomEvent2 listener1A(CustomEvent1 customEvent1) {
        System.out.println("事件监听1A:" + customEvent1);
        return new CustomEvent2("测试2");
    }

    @EventListener(condition = "event.source != '测试1'")
    @Order(0)
    public void listener1B(CustomEvent1 customEvent1) {
        System.out.println("事件监听1B:" + customEvent1);
    }


    @EventListener
    public void listener2(CustomEvent2 customEvent2) {
        System.out.println("事件监听2:" + customEvent2);
    }

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(EventConfiguration.class);
        context.publishEvent(new CustomEvent1("测试1"));
        context.publishEvent(new CustomEvent1("测试2"));
    }
}

3.2.1 泛型与事件的监听

在监听事件时,可以通过事件类型来对事件进行筛选。但是因为泛型的擦除(在运行过程中无法获取实例的泛型类型),无法之间利用泛型来对事件进行筛选。 可以让自定义事件类实现ResolvableTypeProvider接口,来对事件类的实例的类型进行处理,从而来实现通过泛型筛选事件。

public class GenericEvent<T> extends ApplicationEvent implements ResolvableTypeProvider {
    public GenericEvent(T source) {
        super(source);
    }

    @Override
    public ResolvableType getResolvableType() {
        System.out.println("getClass():" + getClass());
        System.out.println("getSource():" + getSource());
        return ResolvableType.forClassWithGenerics(getClass(),ResolvableType.forInstance(getSource()));
    }
}

@Configuration
public class GenericConfiguration {
    @EventListener
    public void listenerOfString(GenericEvent<String> genericEvent) {
        System.out.println("string 监听");
    }

    @EventListener
    public void listenerOfBoolean(GenericEvent<Boolean> genericEvent) {
        System.out.println("Boolean 监听");
    }

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(GenericConfiguration.class);
        context.publishEvent(new GenericEvent<String>("string"));
        System.out.println("------------------------");
        context.publishEvent(new GenericEvent<Boolean>(false));
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1439353.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

32USART串口

目录 一.通信接口 二.时序 三.USART简介 ​编辑四.数据帧 五.起始位侦测和采样位置对齐 &波特率计算 六.相关函数 七.编码格式设置 &#xff08;1&#xff09; UTF-8编码&#xff08;有的软件兼容性不好&#xff09;​编辑 &#xff08;2&#xff09;GB2312编码 八.…

【Nicn的刷题日常】之有序序列合并

1.题目描述 描述 输入两个升序排列的序列&#xff0c;将两个序列合并为一个有序序列并输出。 数据范围&#xff1a; 1≤&#xfffd;,&#xfffd;≤1000 1≤n,m≤1000 &#xff0c; 序列中的值满足 0≤&#xfffd;&#xfffd;&#xfffd;≤30000 0≤val≤30000 输入描述…

前端异步相关知识总结

目录 一、同步和异步简介 同步&#xff08;按顺序执行&#xff09; 异步&#xff08;不按顺序执行&#xff09; 异步出现的原因和需求 二、实现异步的方法 回调函数 Promise 生成器Generators/ yield async await 三、promise和 async await 区别 概念 两者的区别 …

07-Java桥接模式 ( Bridge Pattern )

Java桥接模式 摘要实现范例 桥接模式&#xff08;Bridge Pattern&#xff09;是用于把抽象化与实现化解耦&#xff0c;使得二者可以独立变化 桥接模式涉及到一个作为桥接的接口&#xff0c;使得实体类的功能独立于接口实现类&#xff0c;这两种类型的类可被结构化改变而互不影…

实践动物姿态估计,基于最新YOLOv8全系列【n/s/m/l/x】参数模型开发构建公共场景下行人人员姿态估计分析识别系统

姿态估计&#xff08;PoseEstimation&#xff09;在我们前面的相关项目中涉及到的并不多&#xff0c;CV数据场景下主要还是以目标检测、图像识别和分割居多&#xff0c;最近正好项目中在使用YOLO系列最新的模型开发项目&#xff0c;就想着抽时间基于YOLOv8也开发构建实现姿态估…

Open CASCADE学习|创建多段线与圆

使用Open CASCADE Technology (OCCT)库来创建和显示一些2D几何形状。 主要过程如下&#xff1a; 包含头文件&#xff1a;代码首先包含了一些必要的头文件&#xff0c;这些头文件提供了创建和显示几何形状所需的类和函数。 定义变量&#xff1a;在main函数中&#xff0c;定义…

如何查看端口映射?

端口映射是一种用于实现远程访问的技术。通过将外网端口与内网设备的特定端口关联起来&#xff0c;可以使外部网络用户能够通过互联网访问内部网络中的设备和服务。在网络中使用端口映射可以解决远程连接需求&#xff0c;使用户能够远程访问设备或服务&#xff0c;无论是在同一…

JAVA生产使用登录校验模式

背景 目前我们的服务在用户登录时&#xff0c;会先通过登录接口进行密码校验。一旦验证成功&#xff0c;后端会利用UUID生成一个独特的令牌&#xff08;token&#xff09;&#xff0c;并将其存储在Redis缓存中。同时&#xff0c;前端也会将该令牌保存在本地。在后续的接口请求…

常用对象和常用成员函数

常量对象与常量成员函数来防止修改对象&#xff0c;实现最低权限原则。 在Obj被定义为常量对象的情况下&#xff0c;下面这条语句是错误的。 错误的原因是常量对象一旦初始化后&#xff0c;其值就再也不能改变。因此&#xff0c;不能通过常量对象调用普通成员函数&#xff0c;因…

海外云手机的核心优势

随着5G时代的到来&#xff0c;云计算产业正处于高速发展的时期&#xff0c;为海外云手机的问世创造了一个可信任的背景。在资源有限且需求不断增加的时代&#xff0c;将硬件设备集中在云端&#xff0c;降低个人用户的硬件消耗&#xff0c;同时提升性能&#xff0c;这一点单单就…

得物自研API网关实践之路

一、业务背景 老网关使用 Spring Cloud Gateway &#xff08;下称SCG&#xff09;技术框架搭建&#xff0c;SCG基于webflux 编程范式&#xff0c;webflux是一种响应式编程理念&#xff0c;响应式编程对于提升系统吞吐率和性能有很大帮助; webflux 的底层构建在netty之上性能表…

广度优先搜索(BFS)

力扣刷题之旅&#xff1a;进阶篇&#xff08;二&#xff09; 继续我的力扣刷题之旅&#xff0c;我在进阶篇的第一部分中深入探索了BFS&#xff08;广度优先搜索&#xff09;算法&#xff0c;并感受到了它在图形搜索中的强大威力。现在&#xff0c;我进入了进阶篇的第二部分&am…

百卓Smart管理平台 uploadfile.php 文件上传漏洞复现(CVE-2024-0939)

0x01 产品简介 百卓Smart管理平台是北京百卓网络技术有限公司(以下简称百卓网络)的一款安全网关产品,是一家致力于构建下一代安全互联网的高科技企业。 0x02 漏洞概述 百卓Smart管理平台 uploadfile.php 接口存在任意文件上传漏洞。未经身份验证的攻击者可以利用此漏洞上传…

单片机无线发射的原理剖析

目录 一、EV1527编码格式 二、OOK&ASK的简单了解 三、433MHZ 四、单片机的地址ID 五、基于STC15W104单片机实现无线通信 无线发射主要运用到了三个知识点&#xff1a;EV1527格式&#xff1b;OOk&#xff1b;433MHZ。下面我们来分别阐述&#xff1a; EV1527是数据的编…

Stable Diffusion 模型下载:Samaritan 3d Cartoon SDXL(撒玛利亚人 3d 卡通 SDXL)

文章目录 模型介绍生成案例案例一案例二案例三案例四案例五案例六案例七案例八案例九案例十 下载地址 模型介绍 由“PromptSharingSamaritan”创作的撒玛利亚人 3d 卡通类型的大模型&#xff0c;该模型的基础模型为 SDXL 1.0。 条目内容类型大模型基础模型SDXL 1.0来源CIVITA…

IDEA创建Java类时自动添加注释(作者、年份、月份)

目录 IDEA创建Java类时自动添加注释&#xff08;作者、年份、月份&#xff09;如图&#xff1a; IDEA创建Java类时自动添加注释&#xff08;作者、年份、月份&#xff09; 简单记录下&#xff0c;IDEA创建Java类时自动添加注释&#xff08;作者、年份、月份&#xff09;&#…

@PostMapping/ @GetMapping等请求格式

目录 1.只传一个参数的 第一种 第二种 第三种:表单 2.传整个对象的 2.1修改实体类就是传整个对象过来 2.2新增实体类就是传整个对象过来新增 1.只传一个参数的 第一种 PostMapping("/add/{newsId}")public Result addOne(PathVariable Integer newsId) {}pos…

Spring + Tomcat项目中nacos配置中文乱码问题解决

实际工作的时候碰到了nacos中文乱码的问题&#xff0c;一顿排查最终还是调源码解决了。下面为具体的源码流程&#xff0c;有碰到的可以参考下。 对于nacos配置来说&#xff0c;初始主要源码就在NacosConfigService类中。里面有初始化获取配置content以及设置对应监听器的操作。…

windows中的apache改成手动启动的操作步骤

使用cmd解决安装之后开机自启的问题 services.msc 0. 这个命令是打开本地服务找到apache的服务名称 2 .通过服务名称去查看服务的状态 sc query apacheapache3.附加上关掉和启动的命令&#xff08;换成是你的服务名称&#xff09; 关掉命令 sc stop apacheapache启动命令 …

金融行业专题|证券超融合架构转型与场景探索合集(2023版)

更新内容 更新 SmartX 超融合在证券行业的覆盖范围、部署规模与应用场景。新增操作系统信创转型、Nutanix 国产化替代、网络与安全等场景实践。更多超融合金融核心生产业务场景实践&#xff0c;欢迎阅读文末电子书。 在金融行业如火如荼的数字化转型大潮中&#xff0c;传统架…