- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
- <!-- 以前 (很久) 利用 bean 注册组件 (实体类) id 方便在容器中获取 -->
- <bean id="person" class="com.bean.Person">
- <property name="age" value="18"></property>
- <property name ="name" value="zhangsan"></property>
- </bean>
- </beans>
- // 以前配置文件的方式 (bean.xml)--> 被替换成了类 (看上面)
- @Configuration // 告诉 Spring 这是一个配置类
- public class Mainconfig {
- // 给容器注册一个 bean; 类型为返回值类型, id 默认为方法名
- @Bean("person1")// 指定 id 名
- public Person person() {
- return new Person("王五", 10);
- }
- }
- /**/ 测试
- public class MainTest {
- public static void main(String[] args) {
- // 以前通过加载配置文件去获取
- /*ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
- Person bean = (Person) applicationContext.getBean("person");
- System.out.println(bean);*/
- /*out
- * Person [name=zhangsan, age=18]
- */
- // 基于注解的 config
- AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Mainconfig.class);
- Person bean = applicationContext.getBean(Person.class);
- System.out.println(bean);
- /*out
- * Person [name = 王五, age=10]
- */
- // 获取所有 bean 的 id 名
- String[] beanname = applicationContext.getBeanNamesForType(Person.class);
- for (String name : beanname) {
- System.out.println(name);
- }
- /*out
- person1
- */
- }
- }
来源: http://www.bubuko.com/infodetail-2770640.html