@PropertySource
加载指定配置文件
/*** 单独一个@ConfigurationProperties注解,表示从默认的全局配置文件中获取值注入* @PropertySource则是修改默认的全局配置文件,让@ConfigurationProperties去指定的配置文件获取值注入**/@PropertySource(value = {"classpath:person.properties"})@Component@ConfigurationProperties(prefix = "person")public class Person {// something}
@ImportResource
用于导入Spring的XML配置文件,让该配置文件中定义的bean对象加载到Spring容器中。
该注解必须加载Spring的主程序入口上。
// 主程序代码@ImportResource(locations = {"classpath:beans.xml"})@SpringBootApplicationpublic class HelloWorldApplication {public static void main(String[] args) {SpringApplication.run(HelloWorldApplication.class, args);}}// HelloWorld.java POJO类代码public class HelloWorld {private String name;// get/set/toString 方法}
<!--beans.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="helloWorld" class="com.gmd.beans.HelloWorld"><property name="name" value="Hello World"></property></bean></beans>
实际上,Spring并不推荐你使用这种方式注入bean,Spring推荐使用全注解的方式添加组件,即使用@Configuration注解和@Bean注解的方法。
@Configuration 和 @Bean
/*** @Configuration 指明当前类是一个配置类,就是来替代之前的xml配置文件* 在配置文件中用<bean><bean/>标签添加组件,这里这使用@Bean**/@Configurationpublic class MyApplicationConfig {// 将方法的返回值添加到容器中,容器中这个组件默认的id就是该方法名@Beanpublic HelloWorld helloOne(){HelloWolrd helloworld = new HelloWorld();hellowrold.setName("Hello World One.");return helloworld;}@Beanpublic HelloWorld helloTwo(){HelloWolrd helloworld = new HelloWorld();hellowrold.setName("Hello World Two.");return helloworld;}}// HelloWorld.java POJO类代码public class HelloWorld {private String name;// get/set/toString 方法}// Test方法@Qualifier("helloTwo") // 如果该类注入了多个bean,则需要通过该注解告诉Spring你需要使用那个bean@Autowiredprivate HelloWorld helloWorld;@Autowiredprivate ApplicationContext applicationContext;@Testpublic void TestHelloWorld(){System.out.println(helloWorld);Object helloOne = applicationContext.getBean("helloOne");System.out.println(helloOne);}
