@Configuration
@Bean
/**
* 2. Configuration:
* 2.1. 表明这是一个spring的配置类,spring从当前文件开始加载
* 2.2. 如果手动用容器AnnotationConfigApplicationContext制定该类,则Configuration可不写
* 2.3. 如果spring自动用容器加载,则该注解必须有
*/
public class BaseConfig {
/**
* 将当前方法产生的对象放在容器中:
* 1. 默认key为方法名
*/
@Bean
public Student createStudent() {
return Student
.builder().name("lucy").address("shanxi").build();
}
}
配置文件
aws.sz.region=east.1
aws.sz.price=100$
aws.sz.year=2012
aws.sz.brand=aws
副配置类
/**表明这个类中的参数,是从下面aws.properties文件中去读取*/
@PropertySource(value = "classpath:aws.properties")
public class OtherConfig {
@Value("${aws.sz.region}")
private String region;
@Value("${aws.sz.price}")
private String price;
@Value("${aws.sz.year}")
private String year;
@Value("${aws.sz.brand}")
private String brand;
@Bean
public AWSConfig createAWSConfig() {
return AWSConfig.builder()
.brand(brand).region(region).price(price).year(year).build();
}
}
主配置类
@ComponentScan(basePackages = "com.ioc.pure.annotation")
@Configuration
@Import(OtherConfig.class) // 主配置类中导入
public class BaseConfig {
}
测试类
public class TestDemo {
@Test
public void testConfig() {
ApplicationContext container = new AnnotationConfigApplicationContext(BaseConfig.class);
AWSConfig awsConfig = container.getBean(AWSConfig.class);
System.out.println(awsConfig);
}
}
测试类
package com.ioc.pure.annotation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* 1. RunWith: 将junit的测试换成spring的测试
* 2. ContextConfiguration:
* 2.1 告诉spring的IOC容器的注解配置类
* 2.2 告诉spring的IOC容器的xml配置类
* Spring就会自动加载容器,而不用手动去创建容器
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = BaseConfig.class)
//@ContextConfiguration(locations = "classpath:bean.xml")
public class SpringTest {
@Autowired
private BankService bankService;
@Test
public void testBankService(){
bankService.work();
}
}