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;
    }
}

原文地址:http://www.cnblogs.com/tsangyi/p/16885211.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性