spring4.0之二:@Configuration的使用
從Spring3.0,@Configuration用于定義配置類,可替換xml配置文件,被注解的類內(nèi)部包含有一個或多個被@Bean注解的方法,這些方法將會被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext類進(jìn)行掃描,并用于構(gòu)建bean定義,初始化Spring容器。
注意:@Configuration注解的配置類有如下要求:
一、用@Configuration加載spring
1.1、@Configuration配置spring并啟動spring容器
1.2、@Configuration啟動容器+@Bean注冊Bean
1.3、@Configuration啟動容器+@Component注冊Bean
1.4、使用 AnnotationConfigApplicationContext 注冊 AppContext 類的兩種方法
1.5、配置Web應(yīng)用程序(web.xml中配置AnnotationConfigApplicationContext)
二、組合多個配置類
2.1、在@configuration中引入spring的xml配置文件
2.2、在@configuration中引入其它注解配置
2.3、@configuration嵌套(嵌套的Configuration必須是靜態(tài)類)
三、@EnableXXX注解
四、@Profile邏輯組配置
五、使用外部變量
一、@Configuation加載Spring方法
1.1、@Configuration配置spring并啟動spring容器
@Configuration標(biāo)注在類上,相當(dāng)于把該類作為spring的xml配置文件中的<beans>,作用為:配置spring容器(應(yīng)用上下文)
package com.dxz.demo.configuration;import org.springframework.context.annotation.Configuration;@Configuration public class TestConfiguration {public TestConfiguration() {System.out.println("TestConfiguration容器啟動初始化。。。");} }相當(dāng)于:
<?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false"></beans>主方法進(jìn)行測試:
package com.dxz.demo.configuration;import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestMain {public static void main(String[] args) {// @Configuration注解的spring容器加載方式,用AnnotationConfigApplicationContext替換ClassPathXmlApplicationContextApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);// 如果加載spring-context.xml文件:// ApplicationContext context = new// ClassPathXmlApplicationContext("spring-context.xml"); } }從運(yùn)行主方法結(jié)果可以看出,spring容器已經(jīng)啟動了:
1.2、@Configuration啟動容器+@Bean注冊Bean,@Bean下管理bean的生命周期
@Bean標(biāo)注在方法上(返回某個實例的方法),等價于spring的xml配置文件中的<bean>,作用為:注冊bean對象
bean類:
package com.dxz.demo.configuration;public class TestBean {private String username;private String url;private String password;public void sayHello() {System.out.println("TestBean sayHello...");}public String toString() {return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;}public void start() {System.out.println("TestBean 初始化。。。");}public void cleanUp() {System.out.println("TestBean 銷毀。。。");} }配置類:
package com.dxz.demo.configuration;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope;@Configuration public class TestConfiguration {public TestConfiguration() {System.out.println("TestConfiguration容器啟動初始化。。。");}// @Bean注解注冊bean,同時可以指定初始化和銷毀方法// @Bean(name="testBean",initMethod="start",destroyMethod="cleanUp") @Bean@Scope("prototype")public TestBean testBean() {return new TestBean();} }主方法測試類:
package com.dxz.demo.configuration;import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestMain {public static void main(String[] args) {// @Configuration注解的spring容器加載方式,用AnnotationConfigApplicationContext替換ClassPathXmlApplicationContextApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);// 如果加載spring-context.xml文件:// ApplicationContext context = new// ClassPathXmlApplicationContext("spring-context.xml");//獲取beanTestBean tb = (TestBean) context.getBean("testBean");tb.sayHello();} }結(jié)果:
注:?
(1)、@Bean注解在返回實例的方法上,如果未通過@Bean指定bean的名稱,則默認(rèn)與標(biāo)注的方法名相同;?
(2)、@Bean注解默認(rèn)作用域為單例singleton作用域,可通過@Scope(“prototype”)設(shè)置為原型作用域;?
(3)、既然@Bean的作用是注冊bean對象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注冊bean,當(dāng)然需要配置@ComponentScan注解進(jìn)行自動掃描。
?
@Bean下管理bean的生命周期
可以使用基于 Java 的配置來管理 bean 的生命周期。@Bean?支持兩種屬性,即?initMethod?和destroyMethod,這些屬性可用于定義生命周期方法。在實例化 bean 或即將銷毀它時,容器便可調(diào)用生命周期方法。生命周期方法也稱為回調(diào)方法,因為它將由容器調(diào)用。使用?@Bean?注釋注冊的 bean 也支持 JSR-250 規(guī)定的標(biāo)準(zhǔn)?@PostConstruct?和?@PreDestroy?注釋。如果您正在使用 XML 方法來定義 bean,那么就應(yīng)該使用 bean 元素來定義生命周期回調(diào)方法。以下代碼顯示了在 XML 配置中通常使用 bean 元素定義回調(diào)的方法。
@Configuration @ComponentScan(basePackages = "com.dxz.demo.configuration") public class TestConfiguration {public TestConfiguration() {System.out.println("TestConfiguration容器啟動初始化。。。");}//@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");tb.sayHello();System.out.println(tb);TestBean tb2 = (TestBean) context.getBean("testBean");tb2.sayHello();System.out.println(tb2);} }結(jié)果:
分析:
結(jié)果中的1:表明initMethod生效
結(jié)果中的2:表明@Scope("prototype")生效
?
?
?
1.3、@Configuration啟動容器+@Component注冊Bean
bean類:
package com.dxz.demo.configuration;import org.springframework.stereotype.Component;//添加注冊bean的注解 @Component public class TestBean {private String username;private String url;private String password;public void sayHello() {System.out.println("TestBean sayHello...");}public String toString() {return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;}public void start() {System.out.println("TestBean 初始化。。。");}public void cleanUp() {System.out.println("TestBean 銷毀。。。");} }配置類:
package com.dxz.demo.configuration;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope;@Configuration //添加自動掃描注解,basePackages為TestBean包路徑 @ComponentScan(basePackages = "com.dxz.demo.configuration") public class TestConfiguration {public TestConfiguration() {System.out.println("TestConfiguration容器啟動初始化。。。");}/*// @Bean注解注冊bean,同時可以指定初始化和銷毀方法// @Bean(name="testNean",initMethod="start",destroyMethod="cleanUp")@Bean@Scope("prototype")public TestBean testBean() {return new TestBean();}*/ }主方法測試獲取bean對象:
package com.dxz.demo.configuration;import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestMain {public static void main(String[] args) {// @Configuration注解的spring容器加載方式,用AnnotationConfigApplicationContext替換ClassPathXmlApplicationContextApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);// 如果加載spring-context.xml文件:// ApplicationContext context = new// ClassPathXmlApplicationContext("spring-context.xml");//獲取beanTestBean tb = (TestBean) context.getBean("testBean");tb.sayHello();} }sayHello()方法都被正常調(diào)用。
1.4、使用 AnnotationConfigApplicationContext 注冊 AppContext 類的兩種方法
1.4.1、?配置類的注冊方式是將其傳遞給?AnnotationConfigApplicationContext?構(gòu)造函數(shù)
public static void main(String[] args) {// @Configuration注解的spring容器加載方式,用AnnotationConfigApplicationContext替換ClassPathXmlApplicationContextApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); //獲取beanTestBean tb = (TestBean) context.getBean("testBean");tb.sayHello();}1.4.2、 AnnotationConfigApplicationContext?的register?方法傳入配置類來注冊配置類
public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext();ctx.register(AppContext.class) }1.5、配置Web應(yīng)用程序(web.xml中配置AnnotationConfigApplicationContext)
過去,您通常要利用 XmlWebApplicationContext 上下文來配置 Spring Web 應(yīng)用程序,即在 Web 部署描述符文件 web.xml 中指定外部 XML 上下文文件的路徑。XMLWebApplicationContext 是 Web 應(yīng)用程序使用的默認(rèn)上下文類。以下代碼描述了 web.xml 中指向?qū)⒂?ContextLoaderListener 監(jiān)聽器類載入的外部 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>現(xiàn)在,您要將 web.xml 中的上述代碼更改為使用 AnnotationConfigApplicationContext 類。切記,XmlWebApplicationContext 是 Spring 為 Web 應(yīng)用程序使用的默認(rèn)上下文實現(xiàn),因此您永遠(yuǎn)不必在您的web.xml 文件中顯式指定這個上下文類。現(xiàn)在,您將使用基于 Java 的配置,因此在配置 Web 應(yīng)用程序時,需要在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?現(xiàn)在定義了?AnnotationConfigWebApplicationContext?上下文類,并將其作為上下文參數(shù)和 servlet 元素的一部分。上下文配置位置現(xiàn)在指向?AppContext?配置類。這非常簡單。下一節(jié)將演示 bean 的生命周期回調(diào)和范圍的實現(xiàn)。
1.6、@Configuation總結(jié)
?@Configuation等價于<Beans></Beans>
?@Bean等價于<Bean></Bean>
?@ComponentScan等價于<context:component-scan base-package="com.dxz.demo"/>
?
二、組合多個配置類
2.1、在@configuration中引入spring的xml配置文件
package com.dxz.demo.configuration2;import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource;@Configuration @ImportResource("classpath:applicationContext-configuration.xml") public class WebConfig { }bean類:
package com.dxz.demo.configuration2;public class TestBean2 {private String username;private String url;private String password;public void sayHello() {System.out.println("TestBean2 sayHello...");}public String toString() {return "TestBean2 username:" + this.username + ",url:" + this.url + ",password:" + this.password;}public void start() {System.out.println("TestBean2 初始化。。。");}public void cleanUp() {System.out.println("TestBean2 銷毀。。。");} }測試類:
package com.dxz.demo.configuration2;import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestMain2 {public static void main(String[] args) {// @Configuration注解的spring容器加載方式,用AnnotationConfigApplicationContext替換ClassPathXmlApplicationContextApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);// 如果加載spring-context.xml文件:// ApplicationContext context = new// ClassPathXmlApplicationContext("spring-context.xml");// 獲取beanTestBean2 tb = (TestBean2) context.getBean("testBean2");tb.sayHello();} }結(jié)果:
?2.2、在@configuration中引入其它注解配置
package com.dxz.demo.configuration2;import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.ImportResource;import com.dxz.demo.configuration.TestConfiguration;@Configuration @ImportResource("classpath:applicationContext-configuration.xml") @Import(TestConfiguration.class) public class WebConfig { }測試類:
package com.dxz.demo.configuration2;import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;import com.dxz.demo.configuration.TestBean;public class TestMain2 {public static void main(String[] args) {// @Configuration注解的spring容器加載方式,用AnnotationConfigApplicationContext替換ClassPathXmlApplicationContextApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);// 如果加載spring-context.xml文件:// ApplicationContext context = new// ClassPathXmlApplicationContext("spring-context.xml");// 獲取beanTestBean2 tb2 = (TestBean2) context.getBean("testBean2");tb2.sayHello();TestBean tb = (TestBean) context.getBean("testBean");tb.sayHello();} }結(jié)果:
2.3、@configuration嵌套(嵌套的Configuration必須是靜態(tài)類)
通過配置類嵌套的配置類,達(dá)到組合多個配置類的目的。但注意內(nèi)部類必須是靜態(tài)類。
上代碼:
package com.dxz.demo.configuration3;import org.springframework.stereotype.Component;@Component public class TestBean {private String username;private String url;private String password;public void sayHello() {System.out.println("TestBean sayHello...");}public String toString() {return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;}public void start() {System.out.println("TestBean start");}public void cleanUp() {System.out.println("TestBean destory");} } package com.dxz.demo.configuration3;public class DataSource {private String dbUser;private String dbPass;public String getDbUser() {return dbUser;}public void setDbUser(String dbUser) {this.dbUser = dbUser;}public String getDbPass() {return dbPass;}public void setDbPass(String dbPass) {this.dbPass = dbPass;}@Overridepublic String toString() {return "DataSource [dbUser=" + dbUser + ", dbPass=" + dbPass + "]";} }配置類:
package com.dxz.demo.configuration3;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;@Configuration @ComponentScan(basePackages = "com.dxz.demo.configuration3") public class TestConfiguration {public TestConfiguration() {System.out.println("TestConfiguration容器啟動初始化。。。");} @Configurationstatic class DatabaseConfig {@BeanDataSource dataSource() {return new DataSource();}} }啟動類:
package com.dxz.demo.configuration3;import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestMain {public static void main(String[] args) {// @Configuration注解的spring容器加載方式,用AnnotationConfigApplicationContext替換ClassPathXmlApplicationContextsApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);//beanTestBean tb = (TestBean) context.getBean("testBean");tb.sayHello();DataSource ds = (DataSource) context.getBean("dataSource");System.out.println(ds);} }結(jié)果:
TestConfiguration容器啟動初始化。。。 TestBean sayHello... DataSource [dbUser=null, dbPass=null]3、@EnableXXX注解
配合@Configuration使用,包括 @EnableAsync, @EnableScheduling, @EnableTransactionManagement, @EnableAspectJAutoProxy, @EnableWebMvc。
@EnableAspectJAutoProxy---《spring AOP 之:@Aspect注解》
@EnableScheduling--《Spring 3.1新特性之二:@Enable*注解的源碼,spring源碼分析之定時任務(wù)Scheduled注解》
?
4、@Profile邏輯組配置
見《Spring的@PropertySource + Environment,@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value配合使用》
5、使用外部變量
1、@PropertySource + Environment,通過@PropertySource注解將properties配置文件中的值存儲到Spring的 Environment中,Environment接口提供方法去讀取配置文件中的值,參數(shù)是properties文件中定義的key值。
2、@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value
見《Spring的@PropertySource + Environment,@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value配合使用》
?
總結(jié)
以上是生活随笔為你收集整理的spring4.0之二:@Configuration的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。