使用配置文件时一般是这样写的
<bean id="person" class="com.spring.bean.Person" >
<property name="age" value="18"></property>
<property name="name" value="zhangsan"></property>
</bean>
测试代码
配置的方式
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
Person bean = (Person) ac.getBean("person");
System.out.println(bean);
使用注解需要先定义一个配置类
//配置类 == 配置文件
@Configuration // 告诉spring这个是一个配置类
public class MainConfig {
// 注册一个bean,类型为返回值的类型,id默认用方法名
@Bean
public Person person1() {
return new Person("李思", 50);
}
@Bean("p")
public Person person2() {
return new Person("hhh", 50);
}
@Bean("w")
public Person person3() {
return new Person("呵呵", 50);
}
}
测试类
//定位配置类
ApplicationContext ac = new AnnotationConfigApplicationContext(MainConfig.class);
Person bean = (Person)ac.getBean("p");
System.out.println(Arrays.toString(ac.getBeanNamesForType(Person.class)));