Chapter 05
Section 01 - @Value赋值的应用
entity包下新建一个实体了News,
public class News { private Integer id; private String content; public News() { System.out.println("无参构造方法被调用"); } public News(Integer id, String content) { System.out.println("有参构造方法被调用"); this.id = id; this.content = content; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "News{" + "id=" + id + ", content='" + content + ''' + '}'; } } 复制代码
新建一个配置类BeanValueConfig
@Configuration public class BeanValueConfig { @Bean public News news(){ return new News(); } } 复制代码
新建一个测试类BeanValueConfigTest
public class BeanValueConfigTest { @Test public void getBeanValued(){ ApplicationContext context = new AnnotationConfigApplicationContext(BeanValueConfig.class); System.out.println("IoC容器初始化完成"); String[] beanDefinitionNames = context.getBeanDefinitionNames(); for (String beanDefinitionName : beanDefinitionNames) { System.out.println(beanDefinitionName); } News news = (News) context.getBean("news"); System.out.println(news); } } 复制代码
执行该测试,控制台打印如下,News的属性都为空
使用@Value进行赋值,可以赋值基本数据类型或者Spring的EL表达式
修改News实体类属性部分代码如下,增加@Value注解,并添加值
@Value("1") private Integer id; @Value("某头部主播发布道歉信") private String content; 复制代码
执行BeanValueConfigTest测试,方法控制台打印如下
News对象创建完成之后两个属性都已经被赋值,但是这种情况数据和代码之间的耦合度比较高,因此可以将数据放在配置文件当中,实现数据和代码的解耦。在resources目录下新建config.properties配置文件
news.id=1 news.content=某头部主播各大平台账号被封 复制代码
修改News实体类属性定义部分的代码
@Value("${news.id}") private Integer id; @Value("${news.content}") private String content; 复制代码
修改BeanValueConfig,加载配置文件,设置编码
@Configuration @PropertySource(value = "classpath:config.properties", encoding = "utf-8") public class BeanValueConfig { @Bean public News news(){ return new News(); } } 复制代码
执行测试,控制台输出如下,中文可以正常输出
如果不设置编码格式,中文会出现乱码
配置文件被加载后是放在环境变量中即org.springframework.core.env.Environment类中,可以通过容器获取environemnt对象,通过getProperty获取配置文件中配置项的值 修改测试方法,增加获取environment对象的代码
// 获取环境变量 Environment environment = context.getEnvironment(); System.out.println(environment); System.out.println("new.content配置项的值为:" + environment.getProperty("news.content")); 复制代码
执行测试,查看控制台打印的代码
Section 02 - @Autowired @Resource @Qualifier @Primary自动装配
项目中新建三个包dao,service,controller,分别增加三个类
@Repository public class PersonDao { } 复制代码
@Service public class PersonService { // 自动装配的Bean personDao @Autowired private PersonDao personDao; public PersonDao getBeanByAutowire(){ return personDao; } } 复制代码
@Controller public class PersonController { @Autowired private PersonService personService; } 复制代码
新增配置类BeanAutoAssembleConfig,将新建的三个包中的Bean注册到容器中
@ComponentScan(basePackages = {"com.citi.dao","com.citi.service","com.citi.controller"}) public class BeanAutoAssembleConfig { }