Spring重要特性:IOC/DI (控制反转 / 依赖注入)
传统方式
使用beans.xml
- 创建bean类
package com.example.annotations.bean;
public class Person {
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
- idea中创建beans.xml
new – xml configuration file – Spring config
<bean id="person" class="com.example.annotations.bean.Person">
<property name="name" value="lxl"/>
<property name="age" value="21"/>
</bean>
- 测试
@Test
void beanTest(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
注解方式 @Configuration @Bean
-
编写MainConfig类:配置类等同于beans.xml
package com.example.annotations.config; import com.example.annotations.bean.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; // @Configuration : 告诉Spring这是个配置类 @Configuration public class MainConfig { //给容器注入一个bean,类型为返回值的类型,id默认使用方法的id @Bean("person") public Person getPerson(){ return new Person("qd",21); } }
-
测试
@Test void beanConfigTest(){ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); Person person = applicationContext.getBean(Person.class); //获取对应类型组件在IOC容器中的名字 返回一个数组 String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class); // System.out.println(Arrays.toString(beanNamesForType)); for (String str:beanNamesForType){ System.out.println("toString:" + str.toString()); } }
-
Notes
- @Configuration:告诉Spring这是个配置类
- @Bean:给容器注入一个bean
- 标注在类上:类型为bean类的类型,id默认为类的小写
- 标注在方法上:类型为返回值的类型,id默认使用方法的id