1 配置文件开发回顾
使用配置文件的方式给容器注册bean
- java Bean
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private String name;
private Integer age;
}
- spring配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!--配置一个bean-->
<bean id="person" class="study.wyy.spring.anno.learn.model.Person">
<property name="name" value="Wade"></property>
<property name="age" value="18"></property>
</bean>
</beans>
- 测试
public class Test01 {
@Test
public void testXml(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
// 使用name
Person person = (Person) applicationContext.getBean("person");
Assert.assertThat(person.getName(), equalTo("Wade"));
Assert.assertThat(person.getAge(), equalTo(18));
// 使用class
Person bean = applicationContext.getBean(Person.class);
Assert.assertThat(bean.getName(), equalTo("Wade"));
Assert.assertThat(bean.getAge(), equalTo(18));
}
}
2 使用注解开发
使用注解开发实现给容器注册bean
- 配置类
/**
* @author :wyaoyao
* @date : 2020-06-13 13:24
* Configuration: 表明是一个配置类
*/
@Configuration
public class BeanConfig {
/**
* @Bean : 给容器中注册一个一个bean
* 类型为返回值类型
* id默认为方法名
*
*/
@Bean
Person person(){
Person kobe = new Person("Kobe", 20);
return kobe;
}
}
- 测试
@Test
public void testAnno(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
Person bean = applicationContext.getBean(Person.class);
Assert.assertThat(bean,notNullValue());
Assert.assertThat(bean.getName(), equalTo("Kobe"));
Assert.assertThat(bean.getAge(), equalTo(20));
}