SpringBoot 配置 @PropertySource、@ImportResource、@Bean
阿新 • • 發佈:2018-04-14
conf 指定 system str class return main otc fix
一、@PropertySource
@PropertySource:加載指定的配置文件
@PropertySource(value = {"classpath:person.properties"}) @Component @ConfigurationProperties(prefix = "person") public class Person { }
二、@ImportResource:導入Spring的配置文件,讓配置文件裏面的內容生效
Spring Boot裏面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別;
想讓Spring的配置文件生效,加載進來;@ImportResource標註在一個配置類上
@ImportResource(locations = {"classpath:applicationContext.xml"}) @SpringBootApplication public class SpringBootConfigApplication { public static void main(String[] args) { SpringApplication.run(SpringBootConfigApplication.class, args); } }
三、SpringBoot推薦給容器中添加組件的方式;推薦使用全註解的方式
1、配置類@Configuration------>Spring配置文件
2、使用@Bean給容器中添加組件
/** * @Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件 * * 在配置文件中用<bean><bean/>標簽添加組件 * */ @Configuration public class MyAppConfig { //將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名 @Bean public HelloService helloService(){ System.out.println("配置類@Bean給容器中添加組件了..."); return new HelloService(); } }
SpringBoot 配置 @PropertySource、@ImportResource、@Bean