本文共 2235 字,大约阅读时间需要 7 分钟。
pom.xml
4.0.0 com.zhagndi spring-annotation 0.0.1-SNAPSHOT org.springframework spring-context 4.3.12.RELEASE
beans.xml
Person:
package com.zhangdi.bean;public class Person { private String name; private Integer age; public Person() { super(); // TODO Auto-generated constructor stub } public Person(String name, Integer age) { super(); 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 + "]"; }}
MainConfig.java:
package com.zhangdi.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.zhangdi.bean.Person;/** * @author 张 迪 * */@Configurationpublic class MainConfig { @Bean("person") public Person person() { return new Person("lisi",20); }}
MainTest.java:
package com.zhangdi;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.zhangdi.bean.Person;import com.zhangdi.config.MainConfig;public class MainTest { @SuppressWarnings("resource") public static void main(String[] args) { // TODO Auto-generated constructor stub// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");// Object bean = applicationContext.getBean("Person");// System.out.println(bean); ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); Person bean = applicationContext.getBean(Person.class); System.out.println(bean); String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class); for (String name : beanNamesForType) { System.out.println(name); } }}