zoukankan      html  css  js  c++  java
  • Spring详解(十)----使用@Configuration与@Bean注解装配Bean

    1、@Configuration与@Bean的使用

           @Configuration与@Bean主要用于在 Java 代码中实现 Spring 的配置,它的目的替换Spring的xml配置文件。@Configuration用于定义配置 Spring容器(应用上下文),被它修饰的类表示可以使用 Spring IoC 容器作为 bean 定义的来源,@Bean注解用于注册bean对象,被标记的方法的返回值会作为bean被加入到springIOC容器之中。如果要获取它们,我们可以使用AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。这两者的配合使用会在SpringBoot中大量使用,用来替代XML配置,因为SpringBoot不提倡使用XML配置文件开发。

           下面我们来简单介绍一下这两个注解:

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

           本节我们就来学习如何使用@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对象已经创建成功了。

    2、@import注解

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

           ---新建的GirlFriendConfig类:

    image

           ---PojoConfig类:

    image

           运行结果如下图所示:

    image

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

  • 相关阅读:
    centos安装docker
    centos 安装nginx遇到的问题
    IntelliJ IDEA 2018.3 永久激活 破解[Windows]
    mysql 8.0.12重置密码
    mysql8.*忘记密码
    CentOS安装Hadoop
    执行 systemctl start firewalld 命令后出现Failed to start firewalld.service: Unit is masked
    Centos操作命令
    解决CentOS7关闭/开启防火墙出现Unit iptables.service failed to load: No such file or directory.
    Java并发Lock接口
  • 原文地址:https://www.cnblogs.com/tanghaorong/p/14172974.html
Copyright © 2011-2022 走看看