從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