1.首先创建一个 Person 类,也就是要注入到容器中的 bean。
package bean;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.创建一个 BeanConfig 类,使用 @Configuration 来声明该类是一个配置类,相当于以前的 beans.xml。在配置类的方法上使用 @Bean,就会往容器中注册一个bean,bean 的类型就是该方法的返回值,bean 的名称默认就是方法名。
package config;
import bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanConfig {
@Bean
public Person person() {
return new Person("zhangsan", 28);
}
}
3.查看效果(创建一个 App 类),使用 AnnotationConfigApplicationContext 来获取使用注解配置的 bean。同时可以使用 ApplicationContext 的 getBeanNamesForType(配置类) 方法获取相对应的 bean 名称。
import bean.Person;
import config.BeanConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(BeanConfig.class);
Person person = applicationContext.getBean(Person.class);
System.out.println(person);
String[] beanNames = applicationContext.getBeanNamesForType(Person.class);
for (String beanName : beanNames) {
System.out.println("beanName: " + beanName);
}
}
}
运行结果:
Person{name='zhangsan', age=28}
beanName: person
4.修改 bean 名称的两种方式
// 1. 修改 Bean 名称的第一种方法:直接修改方法名
@Bean
public Person ps() {
return new Person("zhangsan", 28);
}
// 2. 给 @Bean 注解添加 value 值,如 @Bean(value = "ps")
@Bean(value = "ps")
public Person person() {
return new Person("zhangsan", 28);
}