@Configuration 和 @Bean 讲解

本文深入解析Spring框架中@Bean与@Configuration注解的使用方法及其等效的XML配置。介绍了如何利用这些注解来替代XML配置,实现bean的注册与管理,以及不同作用域的设置。

转自
https://blog.youkuaiyun.com/javaloveiphone/article/details/52182899

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

<think>首先,用户的问题是:如何使用@Configuration类注入bean?可能需要示例代码或配置说明。具体来说,他们提到了Spring的@Configuration注解。根据系统级指令:-所有行内数学表达式必须使用$...$格式,但这里涉及的是JavaSpring配置,没有数学内容,所以不需要使用数学格式。-独立公式必须使用$$...$$,但同样不适用。-LaTeX语法正确:不涉及。-使用中文回答。-生成相关问题:系统指令中说“生成相关问题”,所以我在回答后需要添加相关问题。-回答中引用的段落末尾自然地添加引用标识:例如[^1],[^2]等。用户提供了引用[1]、[2]、[3],我需要参考它们。用户提供的引用:-[1]:解释了@Configuration的使用,示例代码创建MyServicebean。-[2]:类似,使用@Bean创建UserServicebean。-[3]:解释了@Configuration的作用:Spring容器识别配置类,调用@Bean方法将对象添加到上下文中。用户说这些引用仅供参考,我应该基于上一次的问题回答来构建。但在这个对话中,这是用户的第一次消息,所以没有之前的上下文。用户的问题是基于这些引用来提问的。关键是要解释如何使用@Configuration类注入bean,并提供示例代码。结构我的回答:1.**介绍@Configuration**:解释它是用来定义配置类的,Spring容器会加载它。2.**步骤**:解释创建配置类的过程:-创建一个带有@Configuration注解的类。-在类中定义方法,用@Bean注解,返回要注入的对象。3.**示例代码**:提供简洁的示例。参考引用,示例类似AppConfig类定义@Bean方法。4.**注入机制**:解释Spring如何自动调用这些方法并将返回值注册为bean。5.**中文回答**:确保用中文。6.**引用标识**:在引用的地方添加[^1],[^2],[^3]。例如,在提到定义时引用[1]或[3]。7.**生成相关问题**:在回答后添加"§§相关问题§§",然后列出2-3个相关问题。系统指令示例中有相关问题。相关问题想法:-如何注入bean时指定作用域?-如何从其他bean访问配置的bean?-@Configurationvs.@Component的区别?基于指令:"生成相关问题",这是必须的。最终回答结构:-清晰讲解步骤。-提供代码块。-添加引用标识。-结束时添加相关问题。</think> ### 如何使用Spring @Configuration注解注入Bean Spring框架中的@Configuration注解用于定义配置类,它允许你使用Java配置方式代替XML文件来声明Bean(即Spring容器管理的对象)。通过在配置类中添加@Bean方法,Spring容器会自动调用这些方法,并将返回的对象注册为Bean,从而实现依赖注入。这样,配置更灵活、类型安全,便于维护。 下面,我将逐步解释如何使用@Configuration类注入Bean,包括创建配置类、定义Bean方法,以及代码示例。解释基于Spring的核心机制:当Spring应用启动时,容器会扫描@Configuration类,执行其@Bean方法,并将返回对象添加到应用上下文供其他组件使用 [^3]。 #### 步骤详解 1. **创建配置类**: - 使用@Configuration注解标记一个类(通常命名为AppConfig或其他)。这个类充当配置源,Spring容器会识别并加载它。 - 在类内部,定义方法(返回类型为Bean的类型),并使用@Bean注解标记。方法体内实例化并返回对象。 2. **定义Bean方法**: - @Bean方法返回的对象将被注册为Spring Bean。Bean名称默认是方法名(如userService),但可以通过@Bean(name = "自定义名称")指定。 - 你可以注入其他依赖到这些方法中(例如,如果UserService需要其他Bean,可以在方法参数中使用@Autowired)。 3. **注入机制**: - Spring容器在启动时,会调用配置类中的所有@Bean方法,并将返回值注册为单例Bean(默认作用域)。其他组件(如@Controller或@Service)可以通过@Autowired或构造函数注入来使用这些Bean。 - 整个过程完全由Spring管理,无需手动创建对象 [^1] [^3]。 #### 示例代码 以下是一个完整的Java配置示例,演示了如何创建@Configuration类并注入两个Bean:UserServiceMyService。代码基于引用中的说明 [^1] [^2]。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; // 定义配置类 @Configuration public class AppConfig { // 注入一个UserService Bean,方法返回的对象将注册为Bean @Bean public UserService userService() { // 创建并返回UserService实例,这里可以添加初始化逻辑 return new UserService(); } // 注入另一个MyService Bean @Bean public MyService myService() { // MyServiceImpl 是MyService接口的实现类 return new MyServiceImpl(); } } ``` #### 代码说明 - **为什么需要@Configuration**:@Configuration让Spring处理Bean的创建生命周期,而不是在代码中硬编码 [^3]。例如,在上面的AppConfig类中,userService()方法返回UserService对象后,Spring会自动将其存储在容器中。 - **如何使用这些Bean**:在其他组件(如Controller)中,只需使用@Autowired注入: ```java @Service public class SomeService { @Autowired private UserService userService; // 从AppConfig注入的Bean public void someMethod() { userService.doSomething(); // 直接使用Bean } } ``` - **配置注意点**: - 确保配置类在Spring扫描路径下(通常在启动类使用@SpringBootApplication或@ComponentScan)。 - 如果Bean有依赖(如需要其他Bean),可以在@Bean方法参数中声明,Spring会自动注入 [^1]。例如: ```java @Bean public ComplexService complexService(MyService myService) { return new ComplexService(myService); // MyService Bean自动传递 } ``` 通过以上方式,@Configuration类提供了声明式的方式来管理Bean依赖,提高了代码的可读性可维护性。类似引用中的解释,@Configuration注解是Spring Java配置的核心 [^2] [^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值