@PropertiesResource & @ImportResource

@ConfigurationProperties(prefix = "person")

@ConfigurationProperties是从全局配置文件(application.xml 或者application.yml)中取配置

-----------------------------------------------分割线-----------------------------------------------

@PropertySource从指定的配置文件中读取

 

最简易版代码:

 

 

 

me.properties:

name=zhangsan
age=18
HiController:
@RestController
@PropertySource(value="classpath:me.properties")
public class HiController {
    @Value("${name}")
    String name;
    @Value("${age}")
    String age;

    @RequestMapping("/hi")
    public String getHi() {
        System.out.println(name);
        System.out.println(age);
        return "";
    }
}

因为在类路径下,所以这里要classpath, 否则会报错找不到这个文件

结果:

 

 

 

但是一般是用来配合bean,给bean注入properties的。所以就在bean上面@Component注入容器。

这个xml:

<bean id="user" class="com.springmvc.bean.User">
    <property name="name" value="zhangsan"/>
    <property name="age" value="18" />
</bean>

等价于代码:

me.properties:

name=zhangsan
age=18
User:
@Component
@PropertySource(value = "classpath:me.properties")
public class User {
    @Value("${name}")
    private String name;
    @Value("${age}")
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

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

验证:

使用Controller测试一下:

@RestController
public class HiController {
    @Autowired
    User user;
    @RequestMapping("/hi")
    public String getHi() {
        return user.getName() + "---" + user.getAge();
    }
}

 

 

-----------------------------------------------分割线-----------------------------------------------

 

@ImportResource:

作用:放在注解类上,将指定的xml加载进容器

写一个bean的xml文件:

<?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 name="b" class="com.shishi.firstservice.bean.Person"></bean>
</beans>

这里用intellij工具写spring的xml文件:

 

 

 

//放在这个配置类上的
@ImportResource(value = {"classpath:beans.xml"})
@SpringBootApplication
public class FirstServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(FirstServiceApplication.class, args);
    }
}

 

最后检查这个配置是否生效了:

@RestController
public class FirstController {

    @Autowired
    ApplicationContext ioc;

    @RequestMapping("/hello")
    public String helloWorld() {
        boolean b = ioc.containsBean("b");
        return b == true ? "yes" : "no";
    }
}

 

posted @ 2020-10-08 21:39  圣金巫灵  阅读(571)  评论(0编辑  收藏  举报