从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,

这些方法将会AnnotationConfigApplicationContext类进行扫描,并用于构建bean定义,

初始化Spring容器。@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>,作用为:配置spring容器(应用上下文)

当然也可为了便于分类配置多个类配置文件。

注意:@Configuration注解的配置类有如下要求:

  1. @Configuration不可以是final类型;
  2. @Configuration不可以是匿名类;
  3. 嵌套的configuration必须是静态类。

一、@Configuration配置spring并启动spring容器

@Configuration
public class TestConfiguration {
public TestConfiguration(){
System.out.println("spring容器启动初始化。。。");
}
}

相当于:

<?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>

主方法进行测试:

public class TestMain {
public static void main(String[] args) { //@Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); //如果加载spring-context.xml文件:
//ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
}
}

运行结果:

二、@Configuration启动容器+@Bean注册Bean,@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的<bean>,作用为:注册bean对象

bean类:

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 销毁。。。");
}
}

配置类:

@Configuration
public class TestConfiguration {
public TestConfiguration(){
System.out.println("spring容器启动初始化。。。");
} //@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替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); // 如果加载spring-context.xml文件:
// ApplicationContext context = new
// ClassPathXmlApplicationContext("spring-context.xml"); //获取bean
TestBean tb = (TestBean) context.getBean("testBean");
tb.sayHello();
}
}

@Bean下管理bean的生命周期

可以使用基于 Java 的配置来管理 bean 的生命周期。@Bean 支持两种属性,即 initMethod 和destroyMethod,这些属性可用于定义生命周期方法。在实例化 bean 或即将销毁它时,容器便可调用生命周期方法。生命周期方法也称为回调方法,因为它将由容器调用。使用 @Bean 注释注册的 bean 也支持 JSR-250 规定的标准 @PostConstruct 和 @PreDestroy 注释。如果您正在使用 XML 方法来定义 bean,那么就应该使用 bean 元素来定义生命周期回调方法。以下代码显示了在 XML 配置中通常使用 bean 元素定义回调的方法。

@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);
}
}

分析:

结果中的1:表明initMethod生效

结果中的2:表明@Scope("prototype")生效

注: 
(1)、@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同; 
(2)、@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域; 
(3)、既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean,

当然需要配置@ComponentScan注解进行自动扫描。

三、@Configuration启动容器+@Component注册Bean

bean类:

package com.test.spring.configuration;

//添加注册bean的注解
@Component
public class TestBean { public void sayHello(){
System.out.println("TestBean sayHello...");
} public String toString(){
return "username:"+this.username+",url:"+this.url+",password:"+this.password;
}
}

配置类:

@Configuration
//添加自动扫描注解,basePackages为TestBean包路径
@ComponentScan(basePackages = "com.test.spring.configuration")
public class TestConfiguration {
public TestConfiguration(){
System.out.println("spring容器启动初始化。。。");
} //取消@Bean注解注册bean的方式
//@Bean
//@Scope("prototype")
//public TestBean testBean() {
// return new TestBean();
//}
}

主方法测试获取bean对象:

public class TestMain {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
//获取bean
TestBean tb = context.getBean("testBean");
tb.sayHello();
}
}

sayHello()方法都被正常调用。

四、使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法

  1. 配置类的注册方式是将其传递给 AnnotationConfigApplicationContext 构造函数

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();
}

  2.AnnotationConfigApplicationContext 的register 方法传入配置类来注册配置类

@Test
public void startSpringContext() {
AnnotationConfigRegistry ctx = new AnnotationConfigApplicationContext();
ctx.register(TestConfiguration.class);
}

  3. 配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext)

  过去,您通常要利用 XmlWebApplicationContext 上下文来配置 Spring Web 应用程序,即在 Web 部署描述符文件 web.xml 中指定外部 XML 上下文文件的路径。XMLWebApplicationContext 是 Web 应用程序使用的默认上下文类。以下代码描述了 web.xml 中指向将由 ContextLoaderListener 监听器类载入的外部 XML 上下文文件的元素。

<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

现在,您要将 web.xml 中的上述代码更改为使用 AnnotationConfigApplicationContext 类。切记,XmlWebApplicationContext 是 Spring 为 Web 应用程序使用的默认上下文实现,因此您永远不必在您的web.xml 文件中显式指定这个上下文类。现在,您将使用基于 Java 的配置,因此在配置 Web 应用程序时,需要在web.xml 文件中指定 AnnotationConfigApplicationContext 类。上述代码将修改如下:

<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>
com.itwang.config.TestConfiguration //这里需要些你的配置类所在位置
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

五、组合多个配置类

1. 在@configuration中引入spring的xml配置文件

@Configuration
@ImportResource("spring.xml")
public class WebConfig {
}

新建一个spring.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-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/aop
http://www.springframework.org/schema/aop/spring-aop-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"> <bean id="testBean2" class="com.itwang.config.TestBean2"></bean>
</beans>

测试

    @Test
public void testSpring() {
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(WebConfig.class);
TestBean2 testBean2 = (TestBean2) applicationContext.getBean("testBean2");
testBean2.sayHello();
}

结果:

2. 在@configuration中引入其它注解配置

@Configuration
@ImportResource("classpath:spring.xml")
@Import(TestConfiguration.class)
public class WebConfig {
}

测试:

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 tb2 = (TestBean2) context.getBean("testBean2");
tb2.sayHello(); TestBean tb = (TestBean) context.getBean("testBean");
tb.sayHello();
}
}

3.  @configuration嵌套(嵌套的Configuration必须是静态类)

通过配置类嵌套的配置类,达到组合多个配置类的目的。但注意内部类必须是静态类。

上代码:

@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");
}
}
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;
}
@Override
public String toString() {
return "DataSource [dbUser=" + dbUser + ", dbPass=" + dbPass + "]";
}
}
//配置类
@Configuration
@ComponentScan(basePackages = "com.dxz.demo.configuration3")
public class TestConfiguration {
public TestConfiguration() {
System.out.println("TestConfiguration容器启动初始化。。。");
} @Configuration
static class DatabaseConfig {
@Bean
DataSource dataSource() {
return new DataSource();
}
}
}

启动类:

public class TestMain {
public static void main(String[] args) { // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContexts
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); //bean
TestBean tb = (TestBean) context.getBean("testBean");
tb.sayHello(); DataSource ds = (DataSource) context.getBean("dataSource");
System.out.println(ds);
}
}

结果:

TestConfiguration容器启动初始化。。。
TestBean sayHello...
DataSource [dbUser=null, dbPass=null]

六、@EnableXXX注解

配合@Configuration使用,包括 @EnableAsync, @EnableScheduling, @EnableTransactionManagement, @EnableAspectJAutoProxy, @EnableWebMvc。

@EnableAspectJAutoProxy---《spring AOP 之:@Aspect注解

@EnableScheduling--《Spring 3.1新特性之二:@Enable*注解的源码,spring源码分析之定时任务Scheduled注解

关于Spring的配置文件的注解使用的更多相关文章

  1. Spring的AOP配置文件和注解实例解析

    1.1           Spring的AOP配置文件和注解实例解析 AOP它利用一种称为"横切"的技术,将那些与核心业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减 ...

  2. spring 学习(二):spring bean 管理--配置文件和注解混合使用

    spring 学习(二)spring bean 管理--配置文件和注解混合使用 相似的,创建 maven 工程,配置pom.xml 文件,具体可以参考上一篇博文: sprint 学习(一) 然后我们在 ...

  3. Struts2 整合Spring(Maven,注解版)

    这两天正在试验Struts2与Spring框架的整合,和他们各自的“注解”.今天就总结一下这两个框架怎么用注解进行整合. 一,加入两者的依赖包,除了两者的必要依赖外,还需要导入struts2-spri ...

  4. Spring Shedule Task之注解实现 (两次启动Schedule Task 的解决方案)

    在spring 中的新引入的task 命名空间.可以部分取代 quartz 功能,配置和API更加简单,并且支持注解方式. 第一步: 在Spring的相关配置文件中(applicationContex ...

  5. [Spring框架]Spring开发实例: XML+注解.

    前言: 本文为自己学习Spring记录所用, 文章内容包括Spring的概述已经简单开发, 主要涉及IOC相关知识, 希望能够对新入门Spring的同学有帮助, 也希望大家一起讨论相关的知识. 一. ...

  6. Spring的配置文件

    Web.xml将会配置Spring的配置文件位置: <servlet>        <servlet-name>x</servlet-name>        & ...

  7. 使用 Spring 2.5 基于注解驱动的 Spring MVC

    http://www.ibm.com/developerworks/cn/java/j-lo-spring25-mvc/ 概述 继 Spring 2.0 对 Spring MVC 进行重大升级后,Sp ...

  8. Spring+AOP+Log4j 用注解的方式记录指定某个方法的日志

    一.spring aop execution表达式说明 在使用spring框架配置AOP的时候,不管是通过XML配置文件还是注解的方式都需要定义pointcut"切入点" 例如定义 ...

  9. 使用 Spring 2.5 基于注解驱动的 Spring MVC--转

    概述 继 Spring 2.0 对 Spring MVC 进行重大升级后,Spring 2.5 又为 Spring MVC 引入了注解驱动功能.现在你无须让 Controller 继承任何接口,无需在 ...

随机推荐

  1. LightOJ 1027 - A Dangerous Maze(求期望)

    题目链接:http://lightoj.com/volume_showproblem.php?problem=1027 题意:又一个迷宫,有n个门,每个门又一个值num,如果num>0 说明在n ...

  2. 洛谷CF264B Good Sequences dp

    解题报告:dp+数论 解题报告: 传送门! 开始看这题的时候想挂了,,,想了个显然是错解的想法,,,就是,我也不知道我怎么想的,鬼迷心窍地就想开个数组存每个质因数的倍数的出现次数,然后排下序的max就 ...

  3. 【Pyton】【小甲鱼】魔法方法

    1.__init__ >>> class Rectangle: def __init__(self,x,y): self.x=x self.y=y def getPeri(self) ...

  4. 在windows中:双击运行Python程序、后台运行Python程序

    在windows中:双击运行Python程序.后台运行Python程序 安装Python解释器的windows环境,如果双击运行*.py的文件,会闪退.怎样避免闪退呢? 我们用python的日志输出程 ...

  5. Laravel和thinkphp的区别/优缺点

    Laravel的设计思想是很先进的,非常适合应用各种开发模式TDD, DDD和BDD,作为使用者最多的php框架,它为你准备好了一切,composer是个php的未来.laravel最大的特点和处优秀 ...

  6. Centos 7(Linux)环境下安装PHP(编译添加)相应动态扩展模块so(以openssl.so为例)

    https://blog.csdn.net/shinesun001/article/details/54312402 在centos 7环境下搭建好Lnmp环境之后,发现安装的php有好多扩展都没有安 ...

  7. XPath轴

    XPath 轴翻译:Linyupark / 2006-03-24 The XML Example DocumentXML举例文档 We will use the following XML docum ...

  8. 让Logstash每次都从头读文件及常见问题

    input { file { path => ["/data/test.log"] start_position => "beginning" si ...

  9. storm介绍,核心组件,编程模型

    一.流式计算概念 利用分布式的思想和方法,对海量“流”式数据进行实时处理,源自业务对海量数据,在“时效”的价值上的挖掘诉求,随着大数据场景应用场景的增长,对流式计算的需求愈发增多,流式计算的一般架构图 ...

  10. [参考资料] 80个Python经典资料(教程+源码+工具)汇总

    AD : 2018重磅地面课程<机器读心术之语音识别前沿实战特训营>,迈向人工智能新高度 [专题推荐]Python系列英文原版电子书 http://down.51cto.com/zt/10 ...