• bean运行时值注入


    1、Environment

    @Configurable
    @PropertySource("classpath:/userinfo.properties") //这个属性文件会加载到Spring的Environment中
    public class UserInfoConfig {
        @Autowired
        private Environment env;
    
        @Bean
        public UserInfo userInfo() {
            return new UserInfo(env.getProperty("user.name1"), Integer.parseInt(env.getProperty("user.age")), env.getProperty("user.sex"));
        }
    }
    

    2、占位符

    @Configurable
    public class UserInfoConfig {
        @Value("${user.name1}")
        private String name;
        @Value("${user.age}")
        private Integer age;
        @Value("${user.sex}")
        private String sex;
    
        @Bean
        public UserInfo userInfo() {
            return new UserInfo(name, age, sex);
        }
    
    /*    @Bean
        public UserInfo userInfo(@Value("${user.name1}") String name, @Value("${user.age}") Integer age, @Value("${user.sex}") String sex) {
            return new UserInfo(name, age, sex);
        }*/
    
        @Bean
        public static PropertySourcesPlaceholderConfigurer placeholder() {
            PropertySourcesPlaceholderConfigurer placeHolder = new PropertySourcesPlaceholderConfigurer();
            placeHolder.setLocation(new FileSystemResource("D:\05-javadev\test20200609_2\src\main\resources\userinfo.properties"));
            //placeHolder.setLocation(new ClassPathResource("classpath:/userinfo.properties"));
            return placeHolder;
        }
    }
    

    3、spel

    public class Student {
        @Value("#{userInfo.name}")
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
        @Bean
        public Student student() {
            Student student = new Student();
            return student;
        }
    
  • 相关阅读:
    C
    C
    如何收集项目日志统一发送到kafka中?
    Jmeter压测快速体验
    实时收集Storm日志到ELK集群
    Neo4j的查询语法笔记(二)
    Logstash2.3.4趟坑之集成Redis哨兵模式
    Spring-Boot中如何使用多线程处理任务
    使用SpringBoot1.4.0的一个坑
    手动从零使用ELK构建一套搜索服务
  • 原文地址:https://www.cnblogs.com/yinchh/p/13073119.html
Copyright © 2020-2023  润新知