@Configuration 与 @Bean 注解的使用技巧

本文详细解析了Spring框架中使用@Configuration和@Bean注解进行容器配置及Bean对象注册的方法,对比了AnnotationConfigApplicationContext与ClassPathXmlApplicationContext的区别,阐述了如何通过@Bean注解注册bean对象及其初始化和销毁过程。

心得 :

1. //@Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext

2.//如果要调用销毁方法必须用子类来声明,而不是ApplicationContext,因为ApplicationContext没有close()        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("com/xxc/initAndDestory/applicationContext.xml");  

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

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

从运行主方法结果可以看出,spring容器已经启动了:

八月 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、@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的<bean>,作用为:注册bean对象

bean类:

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");
        tb.sayHello();
    }
}


注: 
(1)、@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同; 

(2)、@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域; 

(3)、既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean,当然需要配置@ComponentScan注解进行自动扫描。

bean类:

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 {
    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()方法都被正常调用。

 

### 如何通过 @Configuration@Bean 注解定义的 Bean 进行方法调用 在 Spring 中,使用 `@Configuration` 和 `@Bean` 注解可以替代传统的 XML 配置文件来定义和管理 Bean。通过这种方式定义的 Bean 可以被注入到其他组件中,并且可以通过依赖注入的方式调用其方法。 以下是一个完整的示例代码,展示如何通过 `@Configuration` 和 `@Bean` 注解定义 Bean 并调用其方法: ```java // 定义一个简单的类作为 Bean public class Person { private String name; private String id; public Person(String id, String name) { this.id = id; this.name = name; } // 提供一个方法用于调用 public void sayHello() { System.out.println("Hello, my name is " + name + " and my ID is " + id); } } // 使用 @Configuration 注解定义配置类 @Configuration public class BeanConfig { // 使用 @Bean 注解定义一个 Bean @Bean public Person personBean() { return new Person("12345", "John Doe"); } } // 主类用于测试 public class MainApp { public static void main(String[] args) { // 创建 AnnotationConfigApplicationContext 容器 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class); // 从容器中获取 Bean Person person = context.getBean(Person.class); // 调用 Bean 的方法 person.sayHello(); // 关闭上下文 context.close(); } } ``` #### 示例解析 1. **定义 Bean 类**:创建了一个名为 `Person` 的类,并提供了一个 `sayHello` 方法[^1]。 2. **配置类**:使用 `@Configuration` 注解标记的 `BeanConfig` 类作为配置类,在其中使用 `@Bean` 注解的方法返回一个 `Person` 实例[^3]。 3. **获取 Bean 并调用方法**:通过 `AnnotationConfigApplicationContext` 加载配置类,从容器中获取 `Person` Bean,并调用其 `sayHello` 方法[^4]。 ### 注意事项 - 如果未通过 `@Bean` 指定 Bean 的名称,则默认标注的方法名相同。例如,上述代码中 `personBean` 方法对应的 Bean 名称为 `personBean`[^2]。 - 默认情况下,`@Bean` 注解的 Bean 是单例作用域(singleton)。如果需要原型作用域(prototype),可以通过 `@Scope("prototype")` 设置[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值