1、创建一个bean
package com.springbean; public class Person { private String name; private Integer age ; public Person(String name, Integer age) { this.name = name; this.age = age; } public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public Integer getAge() { return age; } @Override public String toString() { return "Person{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } }
2、创建配置类:
import com.springbean.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class PersonConfig { @Bean
//@Bean("myperson") 这是设置bean的名字 public Person person(){ return new Person("张三",20); } }
3、测试
import com.spring.config.PersonConfig; import com.springbean.Person; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class ApplicationTest { public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class); Person bean = applicationContext.getBean(Person.class); System.out.println(bean);
//获取bean的类型,默认是方法名,需要修改就在配置类中@Bean里面加上名字
String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
for (String beanType : beanNamesForType){
System.out.println(beanType);
}
}
}
打完收工
2 |
原文:https://www.cnblogs.com/tdyang/p/11867704.html