@Configuration与@Import
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
}
@Configuration:告诉SpringBoot这是一个配置类,等同于 配置文件
@Import({User.class, DBHelper.class})给容器中自动创建出这两个类型的组件、默认组件名字是全类名
@Conditional条件装配
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = "tom")//没有tom名字的Bean时,MyConfig类的Bean才能生效。
public class MyConfig {
}
条件装配:满足Conditional指定的条件,才进行组件注入
没有tom名字的Bean时,MyConfig类的Bean才能生效。
@ImportResource导入Spring配置文件
若项目原来用bean.xml文件生成配置bean,想继续复用bean.xml,可用@ImportResource
bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans ...">
<bean id="haha" class="com.yhd.boot.bean.User">
<property name="name" value="liming"></property>
<property name="age" value="18"></property>
</bean>
</beans>
使用方法:
@ImportResource("classpath:beans.xml")
public class MyConfig {
...
}
@ConfigurationProperties配置绑定
使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用
传统方法:
public class getProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties pps = new Properties();
pps.load(new FileInputStream("a.properties"));
Enumeration enum = pps.propertyNames();//得到配置文件的名字
while(enum.hasMoreElements()) {
String strKey = (String) enum1.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
//封装到JavaBean
}
}
}
Spring Boot配置绑定方法:
第一种:@ConfigurationProperties + @Component
有配置文件application.properties:
mycar.brand=BYD
mycar.price=100000
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
...
}
第二种:@EnableConfigurationProperties + @ConfigurationProperties
开启Car配置绑定功能
@EnableConfigurationProperties(Car.class)
public class MyConfig {
...
}
把这个Car这个组件自动注册到容器中
@ConfigurationProperties(prefix = "mycar")
public class Car {
...
}