SpringBoot中@PropertiesSource和@ImportResource以及@Bean的用法
1.@PropertiesSource用来导入properties文件中的值
将 person.properties 中的值 , 注入到 person.java 中时 , 使用@PropertiesSource({“classpath:xxx.properties”}) 进行引入 , 贴图如下 :
person.java
package com.lsy.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.Map;
@PropertySource({"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name ;
private int age ;
private Dog dog ;
private Map<String,Object> maps ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", dog=" + dog +
", maps=" + maps +
'}';
}
}
person.properties
person.name = lsy
person.age = 22
person.dog.name=小黑
person.dog.age = 2
person.maps.k1 = v1
person.maps.k2 = v2
2.@ImportResource作用添加 spring 的 xml 配置文件
需要spring 的 xml 配置文件生效 , 使用@ImportResource({“classpath:xxx.xml”}) 在SpringBoot主配置文件进行注册(注 : 可以在 Spring 任何配置类上进行使用)
SpringBootMain
package com.lsy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource({"classpath:bean.xml"})
@SpringBootApplication
public class LsyApplication {
public static void main(String[] args) {
SpringApplication.run(LsyApplication.class, args);
}
}
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 id="myService" class="com.lsy.service.MyService"></bean>
</beans>
这样 SpringBoot 就能将 bean.xml 进行加载 , 便可以在 ioc 容器中管理 MyService 对象
3.@Configuration 是将一个类变成 Spring 配置类 , @Bean 将返回值添加到 spring 的 ioc 容器中
MyConfig.java
package com.lsy.config;
import com.lsy.service.MyService2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
@Bean
public MyService2 myService2(){
return new MyService2() ;
}
}