标签:bean void 利用 注册 property 实体 学习 conf utf-8
<?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
*/
}
}
标签:bean void 利用 注册 property 实体 学习 conf utf-8
原文地址:https://www.cnblogs.com/FellHappy/p/9658555.html