前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spinrgboot配置之@PropertySource和@ImportResource

spinrgboot配置之@PropertySource和@ImportResource

作者头像
西西嘛呦
发布2020-08-26 15:19:28
2580
发布2020-08-26 15:19:28
举报

一、@PropertySource:用于加载指定的配置文件

比如我们在resource下新建一个person.properties

代码语言:javascript
复制
person.username=李四
person.age=12
person.email=zhangsan@qq.com
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=tom
person.dog.age=2

在person.java中

代码语言:javascript
复制
package com.gong.springboot.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

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

//将配置文件中的属性映射到组件中
//prefix:表示配置文件中的哪个下面的属性进行一一映射
@Component
@ConfigurationProperties(prefix="person")
@PropertySource(value={"classpath:person.properties"})
public class Person {
    /**<bean clas="Person">
     *      <property name="username" value="字面量/${key}从环境变量中获取值/#{}spel"></property>
     * </bean>
     *
     */
    //@Value("${person.username}")
    private String username;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("test@qq.com")
    private String email;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }

    public List<Object> getLists() {
        return lists;
    }

    public void setLists(List<Object> lists) {
        this.lists = lists;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    @Override
    public String toString() {
        return "Person{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }
}

注意:@ConfigurationProperties(prefix="person")不要注释掉。同时主配置文件中不能有person.properties相同的配置,否则自己定义的配置就会失效。进行测试:

Person{username='李四', age=12, email='zhangsan@qq.com', maps={k2=v2, k1=v1}, lists=[a, b, c], dog=Dog{name='tom', age=2}}

二、@ImportResource:导入spring的配置文件,让配置文件的内容生效

在com.gong.springboot下新建一个service包,在该包下新建,HelloWorldService.java

代码语言:javascript
复制
package com.gong.springboot.Service;

public class HelloWorldService {
}

在resources文件加下新建beans.xml。将HelloWorldService注入到IOC容器中

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="helloWorldService" class="com.gong.springboot.Service.HelloWorldService"></bean>
</beans>

在主配置类中:

代码语言:javascript
复制
package com.gong.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class Myspringboot2Application {

    public static void main(String[] args) {
        SpringApplication.run(Myspringboot2Application.class, args);
    }

}

在测试文件中:

代码语言:javascript
复制
package com.gong.springboot;

import com.gong.springboot.Service.HelloWorldService;
import com.gong.springboot.bean.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Myspringboot2ApplicationTests {

    @Autowired
    Person person;

    @Autowired
    ApplicationContext ioc;

    @Test
    public void contextLoads() {
        System.out.println(person);
    }

    @Test
    public void testService(){
        Boolean b = ioc.containsBean("helloWorldService");
        System.out.println(b);
    }
}

运行测试:在控制台可以看到输出true。如果不在主配置类中使用ImportResource注解标识位置,则输出的为false。

三、springboot推荐给容器中添加组件的方式:使用全注解的方式

在com.gong.springboot下新建一个config包,在该包下新建MyAppConfig.java

代码语言:javascript
复制
package com.gong.springboot.config;

import com.gong.springboot.Service.HelloWorldService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//指明当前类是一个配置类,替代了之前的spring配置文件,也就是beans.xml
@Configuration
public class MyAppConfig {
    //Bean注解:将方法的返回值添加到容器中,组件默认的id就是方法名,也就是helloWorldService
    @Bean
    public HelloWorldService helloWorldService(){
        return new HelloWorldService();
    }
}

注释掉主配置类中的@ImportResource再进行测试:在控制台还是可以输出true。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-01-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档