spring @Configuration注解、@Bean注解

1,@配置标注在类上,相当于把该类作为弹簧的XML配置文件中的,作用为:配置弹簧容器(应用上下文)<beans>,表明这个类是beans定义的源

从定义看,用于注解类,接口,枚举,注解的定义。

@target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)

package com.test.spring.support.configuration;

@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>
  • 主方法进行测试:
package com.test.spring.support.configuration;

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");
    }
}
  • 从运行主方法结果可以看出,春季容器已经启动了:
八月 11, 2016 12:04:11 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@203e25d3: startup date [Thu Aug 11 12:04:11 CST 2016]; root of context hierarchy
spring容器启动初始化。。。
  • 2,@豆标注在方法上(返回某个实例的方法),等价于弹簧的XML配置文件中的<bean>,作用为:注册豆对象

从定义可以看出,@豆只能用于注解方法和注解的定义。

 
 
@Target({ElementType.METHOD,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)

用@Bean注解的方法:会实例化,配置并初始化一个新的对象,这个对象会由spring IoC容器管理。

@Bean一般和@Component或者@Configuration一起使用,但是在@Component注解的类中不能定义类内依赖的@Bean注解的方法。@配置可以。

相当于在XML文件中配置

<豆>
    <bean id =“TestBean”class =“om.test.spring.support.configuration.TestBean”/>
</豆>

豆类:

package com.test.spring.support.configuration;

public class TestBean {

    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.test.spring.support.configuration;

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

    //@Bean注解注册bean,同时可以指定初始化和销毁方法
    //@Bean(name="testNean",initMethod="start",destroyMethod="cleanUp")
    @Bean
    @Scope("prototype")
    public TestBean testBean() {
        return new TestBean();
    }
}
  • 主方法测试类:
package com.test.spring.support.configuration;

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

(1),@ Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认类名首字母小写; 
(2),@ Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域; 
(3),既然@Bean的作用是注册bean对象,那么完全可以使用@Component,@ Controller,@Service,@Ripository等注解注册bean,当然需要配置@ComponentScan注解进行自动扫描。

豆类:

package com.test.spring.support.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.support.configuration")
public class TestConfiguration {        @Autowired
    TestBean2 testBean;//这样就能使用实体类了
    public TestConfiguration(){
        System.out.println("spring容器启动初始化。。。");
    }


    @PostConstruct
    public void test(){
         testBean.sayHello();
    }

  public static void main(String[] args){
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration2.class);
  }
    //取消@Bean注解注册bean的方式
    //@Bean
    //@Scope("prototype")
    //public TestBean testBean() {
    //  return new TestBean();
    //}
}

注意事项:
	@Configuration 注解的类有一下要求:
	     配置类不能是 final 的
	     配置类不能是本地化的:就是不能将 配置类 定义在 其他类 的方法内部
	     配置类必须有一个无参构造函数


1> 在@configuration中引入xml注解配置 @Configuration
@ImportResource("classpath:config.xml")  
public class StoreConfig {  
    @Value("${jdbc.url}")  
    private String url;  
      
    @Value("${jdbc.username}")  
    private String username;  
      
    @Value("${jdbc.password}")  
    private String password;  
      
    @Bean  
    public MyDriverManager myDriverManager(){  
        return new MyDriverManager(url,username,password);   
    }  
}@ImportResource("")是获得xml文件,但在xml文件中又加载了config.properties配置文件,所以也就间接的加载了config.properties配置文件或者使用注解@PropertySource直接加载配置文件@PropertySource(value={"classpath:/person.properties"})
2>注解配置引入其他的注解配置
@Configuration
@Import(WebSocketConfig.class)
public class WebConfig {
	@Autowired
	WebSocketConfig webSocketConfig;
}

猜你喜欢

转载自blog.csdn.net/qq_31459039/article/details/80107978