zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Spring-通过注解注入Bean的几种方式(二)

Spring注入 方式 通过 几种 注解 bean
2023-06-13 09:14:21 时间

Spring通过注解注入Bean,这里记录一下注入List、Map、String类型的注入

MyBean.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @Author: www.itze.cn
 * @Email: 814565718@qq.com
 */
@Component
public class MyBean {

    //List类型注入方式
    private List<String> list;

    public List<String> getList() {
        return list;
    }

    @Autowired
    @Qualifier(value = "testList")
    public void setList(List<String> list) {
        this.list = list;
    }

    //Map类型注入
    public Map<String,Integer> initMap;

    public Map<String, Integer> getInitMap() {
        return initMap;
    }
    @Autowired
    @Qualifier(value = "springMap")
    public void setInitMap(Map<String, Integer> initMap) {
        this.initMap = initMap;
    }

    //简单数据类型
    private String string;

    public String getString() {
        return string;
    }

    @Value("111")
    public void setString(String string) {
        this.string = string;
    }
}

上下文环境BeanConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: www.itze.cn
 * @Email: 814565718@qq.com
 */
@Configuration
@ComponentScan(value = "com.example.demo")
public class BeanConfig {


    /**
     * 如果需要有List需要注入,Spring会有限考虑第二个String类型
     * 如果同时存在就是需要注入list需要添加BeanId
     *
     * @return
     */
    @Bean
    public List<String> testList() {
        List<String> list = new ArrayList<>();
        list.add("List");
        list.add("类型");
        return list;
    }

    @Bean("springMap")
    public Map<String, Integer> initMap() {
        Map<String, Integer> hashMap = new HashMap<>();
        hashMap.put("aaa", 123);
        hashMap.put("bbb", 456);
        hashMap.put("ccc", 777);
        return hashMap;
    }

    /**
     * @return
     * @Order注解类型int 不需要从下标0开始
     * 不需要连续
     * 值越小优先级越高
     */
    @Bean
    @Order(60)
    public String string1() {
        return "123";
    }

    @Bean
    @Order(50)
    public String string2() {
        return "456";
    }
    //Map类型使用
    @Bean
    public Integer integer1() {
        return 888;
    }

    @Bean
    public Integer integer2() {
        return 999;
    }
}

测试代码Test.java

import com.example.demo.spring.BeanConfig;
import com.example.demo.spring.MyBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.List;
import java.util.Map;

/**
 * @Author: www.itze.cn
 * @Date: 2020/10/14 11:21
 * @Email: 814565718@qq.com
 */
public class Test {

    public static void main(String[] args) {
        //获取Spring上下文
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
        MyBean myBean = applicationContext.getBean("myBean", MyBean.class);
        System.out.println("myBean = " + myBean);
        //List类型
        for (String s : myBean.getList()) {
            System.out.println(s);
        }
        //Map类型
        for (Map.Entry<String, Integer> entry : myBean.getInitMap().entrySet()) {
            System.out.println(entry.getKey());
            System.out.println("value:" + entry.getValue());
        }
        //String类型
        System.out.println(myBean.getString());
        //内部接口
        List testList = myBean.getContext().getBean("testList", List.class);
        System.out.println("======================");
        for (Object o : testList) {
            System.out.println(o);
        }
        /**
         * 输出结果
         * myBean = com.example.demo.spring.MyBean@62da83ed
         * List
         * 类型
         * aaa
         * value:123
         * ccc
         * value:777
         * bbb
         * value:456
         * 111
         * ======================
         * List
         * 类型
         *
         */
    }
}

总结

注入List类型

  1. 在MyBean.java中生成List的Set、Get方法,在Set方法上使用@Autowired注解,告诉Spring上下文环境中需要一个List类型的Bean
  2. 在BeanConfig.java上下文环境中生成List类型的Bean,即创建返回值为List的方法并在方法上方使用@Bean,将该方法交由Spring管理
  3. 在Test.java获取上下文环境后通过getList()方法获取注入的List>>遍历打印输出,List中元素的顺序即为添加时的顺序

注意

  • 如果在BeanConfig.java上下文环境中同时存在List类型的Bean和与注入的List<String>泛型相同Bean(也就是返回结果为String类型的方法的Bean),Spring会优先考虑与注入List类型泛型相同的String类型的Bean,并且将该String类型的Bean的返回值放到List中,因而Test.java测试代码输出结果就是该String类型的Bean的返回值。
  • 如果使用与泛型相同Bean注入,使用@Order控制顺序,@Order注解的值为int类型,值不需要约束从下标0开始,不需要连续,例如:@Order(10)、@Order(20),@Order(10)注解下的值就会排在前面
  • 如果需要BeanConfig.java上下文环境中需要同时存在上面两种情况,那么又想使用List类型的Bean,这个时候需要在MyBean.java注入时,指定Bean,需要使用@Qualifier(value = “testList”),其中value值为Bean的ID,@Bean默认值为方法名,也可以指定,例如:@Bean(“itze”),那么使用这个Bean就是@Qualifier(value = “itze”)

注入Map类型

和注入List类型的大差不差 1. 在MyBean.java中生成Map的Set、Get方法,在Set方法上使用@Autowired注解,告诉Spring上下文环境中需要一个Map类型的Bean 2. 在BeanConfig.java上下文环境中生成Map类型的Bean,即创建返回值为Map的方法并在方法上方使用@Bean,将该方法交由Spring管理 3. 在Test.java获取上下文环境后通过getInitMap()方法获取注入的Map>>遍历打印输出

注意

和List规则也是大差不差 – 如果BeanConfig.java上下文环境中同时存在Map类型的Bean和与注入Map<String,Integer>类型泛型value类型相同的Bean(也就是返回值为Integer类型的方法,在方法上加了@Bean注解),Spring会优先考虑返回值与注入泛型中value类型相同的Bean,并将该Bean的ID作为Map的Key,该Bean的返回值作为Map的Value,因而Test.java测试代码输出Map遍历的结果就是该Integer类型方法名>>>Key,返回值>>>Value – 如果BeanConfig.java上下文环境中同时存在两种类型,又想使用Map类型的Bean,同样方法注入时使用@Qualifier(value = “BeanID”)指定Bean的ID

注入String类型

  1. 同样在MyBean.java中生成String的Set、Get方法,在Set方法上使用@Value(“213”)注解
  2. 在Test.java测试代码中,获取上下文环境之后直接通过getString()获取”213″