1.@PropertySource:加载指定的配置文件;
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "test":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
* @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
*
*/
@PropertySource(value = {"classpath:test.properties"})
@Component
@ConfigurationProperties(prefix = "test")
2.ImportResource:导入Spring的配置文件
Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;
想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上
@ImportResource(locations = {"classpath:beans.xml"})
3.SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式
1、配置类**@Configuration**------>Spring配置文件
2、使用**@Bean**给容器中添加组件
import com.wfbql.demo11.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyAppConfig {
@Bean
public HelloService HelloService(){
//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
return new HelloService();
}
}
@Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件在配置文件中用<bean><bean/>标签添加组件
测试是否活动bean对象
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest
class Demo11ApplicationTests {
//获取容器
@Autowired
ApplicationContext ioc;
@Test
void contextLoads() {
//获取想要的bean对象
System.out.println(ioc.getBean("helloService"));
}
}