Spring详解(十)----使用@Configuration与@Bean注解装配Bean


1、@Configuration与@Bean介绍

@Configuration与@Bean主要用于在 Java 代码中实现 Spring 的配置,它的目的是代替Spring的xml配置文件。下面来简单介绍一下这两个注解:

  • @Configuration:标注在类上,作用:配置Spring容器(应用上下文),被它修饰的类表示可以使用 Spring IoC 容器作为 bean 定义的来源。相当于把该类作为Spring的 xml 配置文件中的<beans>元素(并且包含命名空间)。
  • @Bean:标注在方法上,作用:注册bean对象,被标记的方法的返回值会作为bean被加入到Spring IoC容器之中,bean的名称默认为方法名。相当于把该方法的返回值作为 xml 配置文件中<beans>的子标签<bean>,其中@Bean的配置项中包含 5个配置项:
value:等同于下面的name属性
name:相当于bean的id,<bean id="">,它是一个字符串数组,允许配置多个 BeanName,如果不配置,则默认是方法名
autowire:标志是否是一个引用的 Bean 对象,默认值是 Autowire.NO
initMethod:自定义初始化方法
destroyMethod:自定义销毁方法

如果要获取它们,我们可以使用AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。这两者的配合使用会在SpringBoot中大量使用,用来替代XML配置,因为SpringBoot不提倡使用XML配置文件开发。

2、@Configuration与@Bean举例

本节就来学习如何使用@Configuration与@Bean在Java代码中给容器之中添加Bean。下面简单举例:

①、首先创建一个User类,如下:

/**
 * 用户实体类
 */
public class User {
    private int userId;
    private String userName;
    private int userAge;
    private String userPwd;
    private String userAddress;
    //这里使用注解自动配置
    @Autowired(required = false)
    private GirlFriend girlFriend;
 
    //getter、setter、toString方法省略......
}

②、创建一个GirlFriend类,如下:

/**
 * GirlFriend实体
 */
public class GirlFriend {
    private String girlName;
    private int girlAge;
    private String girlHeight;
 
    //getter、setter、toString方法省略......
}

③、创建PojoConfig类,用来启动容器和注册Bean对象:

package com.thr.pojo;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
@ComponentScan(basePackages = "com.thr.pojo")
@Configuration
public class PojoConfig {
    public PojoConfig() {
        System.out.println("PojoConfig容器初始化成功...");
    }
 
    //实例化User对象并且装配值
    @Bean(name = "user")
    public User user(){
        User user = new User();
        user.setUserId(2021);
        user.setUserName("菜逼小唐");
        user.setUserAge(23);
        user.setUserPwd("asd123");
        user.setUserAddress("地球中国深圳");
        return user;
    }
 
    //实例化GirlFriend对象并且装配值
    @Bean(name ="girlFriend" )
    public GirlFriend girlFriend(){
        GirlFriend girlFriend = new GirlFriend();
        girlFriend.setGirlName("陈美丽");
        girlFriend.setGirlAge(20);
        girlFriend.setGirlHeight("168");
        return girlFriend;
    }
    @Bean(name ="girlFriend1" )
    public GirlFriend girlFriend1(){
        GirlFriend girlFriend1 = new GirlFriend();
        girlFriend1.setGirlName("何美丽");
        girlFriend1.setGirlAge(23);
        girlFriend1.setGirlHeight("170");
        return girlFriend1;
    }
}

上面的PojoConfig.java代码相当于如下的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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
 
    <!--组件自动扫描,指定注解扫描包路径-->
    <!-- base-package放的是包名,有多个包名中间用逗号隔开 -->
    <context:component-scan base-package="com.thr.pojo"/>
 
    <!--实例化GirlFriend-->
    <bean id="girlFriend" class="com.thr.pojo.GirlFriend">
        <property name="girlName" value="陈美丽"/>
        <property name="girlAge" value="20"/>
        <property name="girlHeight" value="168"/>
    </bean>
    <bean id="girlFriend1" class="com.thr.pojo.GirlFriend">
        <property name="girlName" value="何美丽"/>
        <property name="girlAge" value="23"/>
        <property name="girlHeight" value="170"/>
    </bean>
 
    <!--实例化User-->
    <bean id="user" class="com.thr.pojo.User">
        <property name="userId" value="2021"/>
        <property name="userName" value="菜逼小唐"/>
        <property name="userAge" value="23"/>
        <property name="userPwd" value="asd123"/>
        <property name="userAddress" value="地球中国深圳"/>
        <!--这里本来是要注入GirlFriend对象的,这里使用@Autowired注解 自动注入-->
        <!--<property name="girlFriend" ref="girlFriend"/>-->
    </bean>
</beans>

④、测试代码(这里使用AnnotationConfigApplicationContext类来获取):

/**
 * 测试代码
 */
public class SpringTest1 {
    public static void main(String[] args) {
        //1.初始化Spring容器,通过注解加载
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PojoConfig.class);
        //2.通过容器获取实例
        User user =  applicationContext.getBean("user", User.class);
        //3.调用实例中的属性
        System.out.println(user.getUserId()+"----"+
                        user.getUserName()+"----"+
                        user.getUserAge()+"----"+
                        user.getGirlFriend());
    }
}

⑤、运行测试代码,查看控制台打印结果:

image

从上面的运行结果来看,bean对象已经创建成功了。

3、@import注解

@import 注解允许从另一个配置类中加载 @Bean 定义。例如将上面注册的GirlFriend对象拆分到一个GirlFriendConfig类中,然后通过@import注解在PojoConfig类中加载,如下所示:

新建的GirlFriendConfig类:

image

PojoConfig类:

image

运行结果如下图所示:

image

可以发现是先初始化主容器,然后再初始化了外部引入的配置类容器。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM