spring4.0 之 @Configuration注解

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring4.0 之 @Configuration注解相关的知识,希望对你有一定的参考价值。

@Configuration注解与spring-*.xml达到的目的是一样的。@Configuration是为了完全的取消xml配置文件而改用注解。下面将对其进行对比说明:

beans的加载方式

spring-.xml的加载方式:ClassPathXmlApplicationContext、FileSystemXmlApplicationContext、ContextLoaderListener(用于WEB);
纯注解的加载方式:AnnotationConfigApplicationContext、AnnotationConfigWebApplicationContext(用于WEB);

@Configuration与@Bean

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-3.0.xsd" 
     default-lazy-init="true" default-autowire="default">

    <bean id="student" class="com.demo.enity.Student" 
                  init-method="init" destroy-method="destroy" lazy-init="false">
        <property name="age" value="18"/>
        <property name="name" value="test"/>
    </bean>

</beans>
public class Student {
    private Integer age;
    private String name;

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getAge() {
        System.out.println("Age : " + age);
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        System.out.println("Name : " + name);
        return name;
    }

    public void printThrowException() {
        System.out.println("Exception raised");
        throw new IllegalArgumentException();
    }

    public void init(){
        System.out.println("=============Student.init==============");
    }

    public void destroy(){
        System.out.println("=============Student.destroy==============");
    }
}
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-bean.xml");
    Student student = context.getBean(Student.class);
    student.getName();
    student.getAge();

注解配置:

@Configuration
@Lazy
//@Profile("test")
public class BeanConfiguration {
    @Bean(name = "student", initMethod = "init", destroyMethod = "destroy")
    @Scope("prototype")
    public Student student(){
        Student student = new Student();
        student.setAge(100);
        student.setName("this is a test name.");
        return student;
    }
}
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(BeanConfiguration.class);
        annotationConfigApplicationContext.refresh();
        Student student1 = annotationConfigApplicationContext.getBean(Student.class);
        student1.getName();
        student1.getAge();

半xml配置半注解:

@Configuration
@Lazy
//@Profile("test")
public class BeanConfiguration {

    @Bean(name = "student", initMethod = "init", destroyMethod = "destroy")
    @Scope("prototype")
    public Student student(){
        Student student = new Student();
        student.setAge(100);
        student.setName("this is a test name.");
        return student;
    }
}
    <bean class="com.demo.configuration.BeanConfiguration"/>
         <context:annotation-config/>
        <!--或者-->
        <context:component-scan base-package="com.demo"/>
    <context:annotation-config/>
       ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-application.xml");
        Student student2 = context.getBean(Student.class);
        student2.getName();
        student2.getAge();

输出结果:

信息: Loading XML bean definitions from class path resource [spring-bean.xml]
=============Student.init==============
五月 29, 2018 5:13:50 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org[email protected]210366b4: startup date [Tue May 29 17:13:50 CST 2018]; root of context hierarchy
五月 29, 2018 5:13:50 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-application.xml]
Name : test
Age : 18
=============Student.init==============
Name : this is a test name.
Age : 100
五月 29, 2018 5:13:51 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.spring[email protected]2ddc8ecb: startup date [Tue May 29 17:13:51 CST 2018]; root of context hierarchy
=============Student.init==============
Name : this is a test name.
Age : 100

@Configuration与@ComponentScan

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
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.demo"/>

</beans>
@Component
public class Teacher {
    private Integer age;
    private String name;
    private String id;
        。。。
}
ClassPathXmlApplicationContext context4 = 
new ClassPathXmlApplicationContext("classpath:spring-annotation-componentScan.xml");
Teacher teacher4 = context4.getBean(Teacher.class);
System.out.println("teacher4.hashCode = ["+teacher4.hashCode()+"]");

注解配置:

@Configuration
@ComponentScan("com.demo")
public class ComponentScanConfig {
}
        AnnotationConfigApplicationContext context5 = new AnnotationConfigApplicationContext();
        context5.register(ComponentScanConfig.class);
        context5.refresh();
        Teacher teacher5 = context5.getBean(Teacher.class);
        System.out.println("teacher5.hashCode = ["+teacher5.hashCode()+"]");

测试结果:

五月 29, 2018 5:29:15 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org[email protected]4439f31e: startup date [Tue May 29 17:29:15 CST 2018]; root of context hierarchy
五月 29, 2018 5:29:15 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-annotation-componentScan.xml]
五月 29, 2018 5:29:15 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
信息: Overriding bean definition for bean ‘student‘ with a different definition: replacing [Generic bean: class [com.demo.enity.Student]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [E:\idea-projects\springdemo\target\classes\com\demo\enity\Student.class]] with [Root bean: class [null]; scope=prototype; abstract=false; lazyInit=true; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=beanConfiguration; factoryMethodName=student; initMethodName=init; destroyMethodName=destroy; defined in com.demo.configuration.BeanConfiguration]
teacher4.hashCode = [464400749]
五月 29, 2018 5:29:16 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.spring[email protected]50dfbc58: startup date [Tue May 29 17:29:16 CST 2018]; root of context hierarchy
五月 29, 2018 5:29:16 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
信息: Overriding bean definition for bean ‘student‘ with a different definition: replacing [Generic bean: class [com.demo.enity.Student]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [E:\idea-projects\springdemo\target\classes\com\demo\enity\Student.class]] with [Root bean: class [null]; scope=prototype; abstract=false; lazyInit=true; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=beanConfiguration; factoryMethodName=student; initMethodName=init; destroyMethodName=destroy; defined in class path resource [com/demo/configuration/BeanConfiguration.class]]
Disconnected from the target VM, address: ‘127.0.0.1:50240‘, transport: ‘socket‘
teacher5.hashCode = [552937500]

以上是关于spring4.0 之 @Configuration注解的主要内容,如果未能解决你的问题,请参考以下文章

项目ITP spring4.0 整合 Quartz 实现动态任务调度

spring4.0之三:@RestController

Spring4.0 整合Quartz2.2.1

Spring4.0系列5-@Conditional

Spring4.0学习笔记 —— 自动装配

Hibernate总结之常用API