• SpringBoot注入


    SpringBoot属性注入

    涉及注解:
    @Configuration:声明一个类作为配置类
    @Bean:声明在方法上,将方法的返回值加入Bean容器
    @Value:属性注入
    @ConfigurationProperties(prefix = “jdbc”):批量属性注入
    @EnableConfigurationProperties(JdbcProperties.class)声明要使用JdbcProperties这个类的对象(ConfigurationProperties注解的Properties(类)
    @PropertySource(“classpath:jdbc.properties”)指定外部属性文件。在类上添加

    1. @Value注解
    @Configuration
    @PropertySource("classpath:jdbc.properties")
    public class JdbcConfiguration {
    
        @Value("${jdbc.url}")
        String url;
        @Value("${jdbc.driverClassName}")
        String driverClassName;
        @Value("${jdbc.username}")
        String username;
        @Value("${jdbc.password}")
        String password;
    
        @Bean
        public DataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(url);
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        }
    }
    
    

    @Configuration:声明JdbcConfiguration是一个配置类。

    @Value为属性注入值。

    @Bean将 dataSource()方法声明为一个注册Bean的方法,Spring会自动调用该方法,将方法的返回值加入Spring容器中。相当于以前的bean标签,然后可以在任意位置通过@Autowired注入DataSource并使用!

    @PropertySource:指定属性文件的路径是:classpath:jdbc.properties

    (默认不支持指定yml文件,可以通过新增yml工厂类指定),如下:

    public class YamlPropertySourceFactory implements PropertySourceFactory {
        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {
            Resource resource = encodedResource.getResource();
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource);
            Properties props = factory.getObject();
            return new PropertiesPropertySource(resource.getFilename(), props);
        }
    }
    
    @Data
    @Configuration
    @PropertySource(value = "classpath:my.yml", factory = YamlPropertySourceFactory.class)
    @ConfigurationProperties(prefix = "jdbc")
    public class JdbcProperties {
        private String url;
        private String driverClassName;
        private String username;
        private String password;
    }
    
    

    其中@Configuration 、@PropertySource可省略,例如:
    第一步:在yml中自定义测试数据

    自定义属性

    
    person:
      name: reindeer
      age: 18
      hobby: 1、看书, 2、跑步
      infos: "{'phone':'18222222222','address':'河南省郑州市'}"
    
    

    第二步:在Controller中注入属性

    
    @RestController
    @RequestMapping("/test")
    public class TestController {
        @Value("${person.name}")
        private String name;
        @Value("${person.age}")
        private int age;
        @Value("${person.hobby}")
        private List<String> hobby;
        @Value("#{${person.infos}}")
        private Map<String, String> info; //注入的属性为Map集合,则需要结合Spel表达式进行处理
    
        @GetMapping("/show")
        public Map<String, Object> show() {
            Map<String, Object> map = new HashMap<>();
            map.put("name", name);
            map.put("age", age);
            map.put("hobby", hobby);
            map.put("info", info);
            return map;
        }
    }
    
    
    1. Environment对象注入

    第一步:定义数据

    server:
      port: 18080
    
    

    第二步:注入Environment对象,通过getProperty方法()获取

    @RestController("/test2")
    public class Demo02 {
        @Autowired
        private Environment env;
    
        @GetMapping("/show")
        public String show() {
            return "端口:"+env.getProperty("server.port");
        }
    }
    
    
    1. @ConfigurationProperties注解注入
      第一步:创建JdbcProperties类,注入自定义内容
    @ConfigurationProperties(prefix = "jdbc")
    public class JdbcProperties {
        private String url;
        private String driverClassName;
        private String username;
        private String password;
        // ... 略
        // getters 和 setters
    }
    
    

    在类上通过@ConfigurationProperties注解声明当前类为属性读取类

    prefix="jdbc"读取属性文件中,前缀为jdbc的值。

    在类上定义各个属性,名称必须与属性文件中jdbc.后面部分一致,并且必须具有getter和setter方法

    需要注意的是,这里我们并没有指定属性文件的地址,SpringBoot默认会读取文件名为application.properties的资源文件。

    注意:也可以使用 @PropertySource注解指定properties文件,如果不指定默认读取application.yml或者application.properties,如果要指定yml文件,可以通过新增yml工厂类指定

    第二步:使用JdbcProperties这个属性

    通过@EnableConfigurationProperties(JdbcProperties.class)来声明要使用JdbcProperties这个类的对象

    然后通过以下四种方式在JdbcConfiguration类中注入JdbcProperties:

    3.1 @Autowired注入

    @Configuration
    @EnableConfigurationProperties(JdbcProperties.class)
    public class JdbcConfiguration {
    
        @Autowired
        private JdbcProperties jdbcProperties;
    
        @Bean
        public DataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(jdbcProperties.getUrl());
            dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
            dataSource.setUsername(jdbcProperties.getUsername());
            dataSource.setPassword(jdbcProperties.getPassword());
            return dataSource;
        }
    
    }
    

    3.2 构造函数注入

    @Configuration
    @EnableConfigurationProperties(JdbcProperties.class)
    public class JdbcConfiguration {
    
        private JdbcProperties jdbcProperties;
    
        public JdbcConfiguration(JdbcProperties jdbcProperties){
            this.jdbcProperties = jdbcProperties;
        }
    
        @Bean
        public DataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(jdbcProperties.getUrl());
            dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
            dataSource.setUsername(jdbcProperties.getUsername());
            dataSource.setPassword(jdbcProperties.getPassword());
            return dataSource;
        }
    
    }
    

    3.3 @Bean方法的参数注入

    @Configuration
    @EnableConfigurationProperties(JdbcProperties.class)
    public class JdbcConfiguration {
        @Bean
        public DataSource dataSource(JdbcProperties jdbcProperties) {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(jdbcProperties.getUrl());
            dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
            dataSource.setUsername(jdbcProperties.getUsername());
            dataSource.setPassword(jdbcProperties.getPassword());
            return dataSource;
        }
    }
    

    3.4 在需要的方法上注入

    如果属性只有一个Bean需要使用,我们无需将其注入到一个(JdbcProperties)中。而是直接在需要的地方声明即可,此时与JdbcProperties已经无关

    @Configuration
    public class JdbcConfiguration {  
        // 声明要注入的属性前缀,SpringBoot会自动把相关属性通过set方法注入到DataSource中
        // 使用的前提是:该类必须有对应属性的set方法!
        @Bean    
        @ConfigurationProperties(prefix = "jdbc")
        public DataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            return dataSource;
        }
    }
    
  • 相关阅读:
    spark学习(9)-spark的安装与简单使用
    Hadoop学习(8)-scala环境配置及简单使用
    Hadoop学习(7)-hive的安装和命令行使用和java操作
    Hadoop学习(5)-zookeeper的安装和命令行,java操作
    Hadoop学习(6)-HBASE的安装和命令行操作和java操作
    Hadoop学习(4)-mapreduce的一些注意事项
    Hadoop学习(3)-mapreduce快速入门加yarn的安装
    Hadoop学习(2)-java客户端操作hdfs及secondarynode作用
    python执行Linux命令
    python写的百度贴吧邮箱采集(带界面)
  • 原文地址:https://www.cnblogs.com/tsangyi/p/16885211.html
Copyright © 2020-2023  润新知