在类上添加注解@Configuration,代替xml配置中的beans
@Configuration
public class ConfigurationDemo {
ConfigurationDemo(){
System.out.println("加载完成");
}
}
在测试类加载本类
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestDemoApplicationTests {
@Test
public void contextLoads() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ConfigurationDemo.class);
}
}
在方法上添加@Bean,代替xml配置中的bean <bean id=" " class=" ">
@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同
/**
* 写一个类
*/
public class TestPojo {
private Integer id;
private String name;
public void sayHi() {
System.out.println("hi");
}
}
/**
*在有@Configuration注解修饰的类中写一个被@Bean修饰的方法
*/
@Configuration
public class ConfigurationDemo {
ConfigurationDemo(){
System.out.println("加载完成");
}
@Scope("prototype")
@Bean //等价于 <bean id="testPojo" class="TestPojo">
public TestPojo testPojo() {
return new TestPojo();
}
}
/**
*测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestDemoApplicationTests {
@Test
public void contextLoads() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ConfigurationDemo.class);
TestPojo tp = (TestPojo)ac.getBean("testPojo");
tp.sayHi();
}
}
当需要将第三方对象交给spring容器管理时,常常需要用到@Configuration和@Bean
例子:使用第三方的Redis
@Configuration //表示我是一个配置类
@PropertySource("classpath:/properties/redis.properties") //读取配置文件
public class RedisConfig {
@Value("${redis.host}") //获取配置文件中的主机号
private String host;
@Value("${redis.port}") //获取配置文件中的端口号
private int port;
@Bean
public Jedis jedis() {
return new Jedis(host,port);//创建一个Redis对象
}
}