从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。html
注意:@Configuration注解的配置类有以下要求:web
@Configuration标注在类上,至关于把该类做为spring的xml配置文件中的,做用为:配置spring容器(应用上下文)spring
package com.cqupt.meeting.config; import org.springframework.context.annotation.Configuration; /** * @Author: ranjun * @Date: 2019/5/12 14:44 */ @Configuration public class TestConfig { public TestConfig(){ System.out.println("testconfig collection init success"); } } 复制代码
至关于bash
<?xml version="1.0" encoding="UTF-8"?> <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" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false"> </beans> 复制代码
主方法进行测试:markdown
package com.cqupt.meeting.config; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * @Author: ranjun * @Date: 2019/5/12 14:46 */ public class Main { public static void main(String[] args) { // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class); // 若是加载spring-context.xml文件: // ApplicationContext context = new // ClassPathXmlApplicationContext("spring-context.xml"); } } 复制代码
从运行主方法结果能够看出,spring容器已经启动了:session
WARNING: All illegal access operations will be denied in a future release testconfig collection init success Process finished with exit code 0 复制代码
@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的,做用为:注册bean对象app
bean类:函数
package com.cqupt.meeting.config; /** * @Author: ranjun * @Date: 2019/5/12 14:54 */ public class TestBean { private String username; private String url; private String password; public void sayHello() { System.out.println("TestBean sayHello..."); } public void start() { System.out.println("TestBean init..."); } public void cleanup() { System.out.println("TestBean destroy..."); } } 复制代码
配置类:为TestConfig类添加方法oop
// @Bean注解注册bean,同时能够指定初始化和销毁方法 // @Bean(name="testBean",initMethod="start",destroyMethod="cleanup") //name属性至关于<bean>标签的id @Bean @Scope("prototype") public TestBean testBean() { return new TestBean(); } } 复制代码
测试:源码分析
public class Main { public static void main(String[] args) { // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class); // 若是加载spring-context.xml文件: // ApplicationContext context = new // ClassPathXmlApplicationContext("spring-context.xml"); //获取bean TestBean testBean = (TestBean) context.getBean("testBean"); testBean.sayHello(); } } 结果: testconfig collection init success TestBean sayHello... Process finished with exit code 0 复制代码
注:
(1)、@Bean注解在返回实例的方法上,若是未经过@Bean指定bean的名称,则默认与标注的方法名相同(第一个单词转小写);
(2)、@Bean注解默认做用域为单例singleton做用域,可经过@Scope(“prototype”)设置为原型做用域;
(3)、既然@Bean的做用是注册bean对象,那么彻底可使用@Component、@Controller、@Service、@Ripository等注解注册bean,固然须要配置@ComponentScan注解进行自动扫描。
scope属性
1). singleton属性值(掌握):默认值,单例
2). prototype属性值(掌握):多例(原型做用域)
3). request属性值(了解):建立对象,把对象放到request域里
4). session属性值(了解):建立对象,把对象放到session域里
5). globalSession属性值(了解):建立对象,把对象放到globalSession域里
@Bean下管理bean的生命周期
可使用基于 Java 的配置来管理 bean 的生命周期。@Bean 支持两种属性,即 initMethod 和destroyMethod,这些属性可用于定义生命周期方法。在实例化 bean 或即将销毁它时,容器即可调用生命周期方法。生命周期方法也称为回调方法,由于它将由容器调用。使用 @Bean 注释注册的 bean 也支持 JSR-250 规定的标准 @PostConstruct 和 @PreDestroy 注解。若是您正在使用 XML 方法来定义 bean,那么就应该使用 bean 元素来定义生命周期回调方法。如下代码显示了在 XML 配置中一般使用 bean 元素定义回调的方法。
//@Bean注解注册bean,同时能够指定初始化和销毁方法 @Bean(name="testBean",initMethod="start",destroyMethod="cleanUp") @Scope("prototype") public TestBean testBean() { return new TestBean(); } 复制代码
启动测试类:
public class TestMain { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); TestBean tb = (TestBean) context.getBean("testBean"); System.out.println(tb); TestBean tb2 = (TestBean) context.getBean("testBean"); System.out.println(tb2); } } 结果: testconfig collection init success TestBean init... com.cqupt.meeting.config.TestBean@5852c06f TestBean init... com.cqupt.meeting.config.TestBean@4149c063 Process finished with exit code 0 复制代码
分析:
结果中的1:代表initMethod生效
结果中的2:代表@Scope("prototype")生效
bean类
package com.cqupt.meeting.config; import org.springframework.stereotype.Component; /** * @Author: ranjun * @Date: 2019/5/12 14:54 */ //添加注册bean的注解 @Component public class TestBean { private String username; private String url; private String password; public void sayHello() { System.out.println("TestBean sayHello..."); } public void start() { System.out.println("TestBean init..."); } public void cleanup() { System.out.println("TestBean destroy..."); } } 复制代码
配置类:
package com.cqupt.meeting.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; /** * @Author: ranjun * @Date: 2019/5/12 14:44 */ @Configuration //添加自动扫描注解,basePackages为TestBean包路径 @ComponentScan(basePackages = "com.cqupt.meeting.config") public class TestConfig { public TestConfig(){ System.out.println("testconfig collection init success"); } // @Bean注解注册bean,同时能够指定初始化和销毁方法 // @Bean(name="testBean",initMethod="start",destroyMethod="cleanup") //// @Bean // @Scope("prototype") // public TestBean testBean() { // return new TestBean(); // } } 复制代码
主方法测试获取bean对象:
public class Main { public static void main(String[] args) { // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class); // 若是加载spring-context.xml文件: // ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml"); //获取bean TestBean testBean1 = (TestBean) context.getBean("testBean"); testBean1.sayHello(); } } 结果: testconfig collection init success TestBean sayHello... Process finished with exit code 0 复制代码
sayHello()方法被正常调用
public static void main(String[] args) { // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); //获取bean TestBean tb = (TestBean) context.getBean("testBean"); tb.sayHello(); } 复制代码
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppContext.class)
}
复制代码
过去,您一般要利用 XmlWebApplicationContext 上下文来配置 Spring Web 应用程序,即在 Web 部署描述符文件 web.xml 中指定外部 XML 上下文文件的路径。XMLWebApplicationContext 是 Web 应用程序使用的默认上下文类。如下代码描述了 web.xml 中指向将由 ContextLoaderListener 监听器类载入的外部 XML 上下文文件的元素。
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>sampleServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
...
</web-app>
复制代码
如今,您要将 web.xml 中的上述代码更改成使用 AnnotationConfigApplicationContext 类。切记,XmlWebApplicationContext 是 Spring 为 Web 应用程序使用的默认上下文实现,所以您永远没必要在您的web.xml 文件中显式指定这个上下文类。如今,您将使用基于 Java 的配置,所以在配置 Web 应用程序时,须要在web.xml 文件中指定 AnnotationConfigApplicationContext 类。上述代码将修改以下:
<web-app>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.
support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
demo.AppContext
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>sampleServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.
support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
</servlet>
...
</web-app>
复制代码
以上修改后的 web.xml 如今定义了 AnnotationConfigWebApplicationContext 上下文类,并将其做为上下文参数和 servlet 元素的一部分。上下文配置位置如今指向 AppContext 配置类。这很是简单。下一节将演示 bean 的生命周期回调和范围的实现。
@Configuation等价于
@Bean等价于
@ComponentScan等价于<context:component-scan base-package="com.dxz.demo"/>
package com.cqupt.meeting.config; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; /** * @Author: ranjun * @Date: 2019/5/12 20:31 */ @Configuration @ImportResource("classpath:configtest.xml") public class WebConfig { public WebConfig(){ System.out.println("WebConfig coolection init success"); } } 复制代码
TestBean2:
package com.cqupt.meeting.config; /** * @Author: ranjun * @Date: 2019/5/12 20:32 */ public class TestBean2 { private String username; private String url; private String password; public void setUsername(String username) { this.username = username; } public void setUrl(String url) { this.url = url; } public void setPassword(String password) { this.password = password; } public void sayHello() { System.out.println("TestBean2 sayHello..."+username); } public void start() { System.out.println("TestBean2 init..."); } public void cleanUp() { System.out.println("TestBean2 destroy..."); } } 复制代码
configtest.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="testBean2" class="com.cqupt.meeting.config.TestBean2"> <property name="username" value="ranjun"></property> </bean> </beans> 复制代码
测试类:
public class TestMain2 { public static void main(String[] args) { // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext ApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class); // 若是加载spring-context.xml文件: // ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml"); // 获取bean TestBean2 tb = (TestBean2) context.getBean("testBean2"); tb.sayHello(); } } 结果: WebConfig coolection init success TestBean2 sayHello...ranjun Process finished with exit code 0 复制代码
@Configuration @ImportResource("classpath:configtest.xml") @Import(TestConfig.class) public class WebConfig { public WebConfig(){ System.out.println("WebConfig coolection init success"); } } 复制代码
TestConfig:
@Configuration //添加自动扫描注解,basePackages为TestBean包路径 //@ComponentScan(basePackages = "com.cqupt.meeting.config") public class TestConfig { public TestConfig(){ System.out.println("testconfig collection init success"); } // @Bean注解注册bean,同时能够指定初始化和销毁方法 // @Bean(name="testBean",initMethod="start",destroyMethod="cleanup") @Bean @Scope("prototype") public TestBean testBean() { return new TestBean(); } } 复制代码
测试类:
public class TestMain2 { public static void main(String[] args) { // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext ApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class); // 若是加载spring-context.xml文件: // ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml"); // 获取bean TestBean tb = (TestBean) context.getBean("testBean"); tb.sayHello(); TestBean2 tb2 = (TestBean2) context.getBean("testBean2"); tb2.sayHello(); } } 结果: WebConfig coolection init success testconfig collection init success TestBean sayHello... TestBean2 sayHello...ranjun Process finished with exit code 0 复制代码
能够看到三个容器都成功启动了
经过配置类嵌套的配置类,达到组合多个配置类的目的。==但注意内部类必须是静态类==。
上代码:
@Configuration //添加自动扫描注解,basePackages为TestBean包路径 //@ComponentScan(basePackages = "com.cqupt.meeting.config") public class TestConfig { public TestConfig(){ System.out.println("testconfig collection init success"); } // @Bean注解注册bean,同时能够指定初始化和销毁方法 // @Bean(name="testBean",initMethod="start",destroyMethod="cleanup") @Bean @Scope("prototype") public TestBean testBean() { return new TestBean(); } @Configuration static class InnerConfig { @Bean TestBean2 testBean2() { TestBean2 testBean2 = new TestBean2(); testBean2.setUsername("ranjun"); return testBean2; } } } 复制代码
测试类:
public class TestMain { public static void main(String[] args) { // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class); // 若是加载spring-context.xml文件: // ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml"); //获取bean TestBean testBean1 = (TestBean) context.getBean("testBean"); testBean1.sayHello(); TestBean2 testBean2 = (TestBean2)context.getBean("testBean2"); testBean2.sayHello(); } } 结果: testconfig collection init success TestBean sayHello... TestBean2 sayHello...ranjun Process finished with exit code 0 复制代码
配合@Configuration使用,包括 @EnableAsync, @EnableScheduling, @EnableTransactionManagement, @EnableAspectJAutoProxy, @EnableWebMvc。
@EnableAspectJAutoProxy--- spring AOP 之二:@AspectJ注解的3种配置
@EnableScheduling--《Spring 3.1新特性之二:@Enable*注解的源码,spring源码分析之定时任务Scheduled注解
一、@PropertySource + Environment,经过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。
二、@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value