根据容器中id名获取对象
<?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对象,Spring自动创建该对象-->
<!--class:注册组件的全类名-->
<!--id:该组件的唯一标识-->
<bean id="person1" class="helloWorld.Person">
<property name="name" value="张三"></property>
<property name="age" value="18"></property>
</bean>
</beans>
public static void main(String[] args) {
//当前应用的xml配置文件在类路径下
ApplicationContext ioc=new ClassPathXmlApplicationContext("ioc.xml");
//获取当前容器中id名为person1的对象
Person p=(Person) ioc.getBean("person1");
System.out.println(p);
}
根据bean类型获取对象
public static void main(String[] args) {
//当前应用的xml配置文件在类路径下
ApplicationContext ioc=new ClassPathXmlApplicationContext("ioc.xml");
//获取当前容器中id名为person1的对象
Person p=ioc.getBean(Person.class);
System.out.println(p);
}
注意,这么获取bean对象,如果有2个相同对象bean写在xml中,那么就会报错。
双管齐下获取
public static void main(String[] args) {
//当前应用的xml配置文件在类路径下
ApplicationContext ioc=new ClassPathXmlApplicationContext("ioc.xml");
//获取当前容器中id名为person1的对象
Person p=ioc.getBean("person1",Person.class);
System.out.println(p);
}
利用有参构造器创建对象
创建构造器
public Person(String name, int age) {
this.name = name;
this.age = age;
}
获取对象
public static void main(String[] args) {
//当前应用的xml配置文件在类路径下
ApplicationContext ioc=new ClassPathXmlApplicationContext("ioc.xml");
//获取当前容器中id名为person1的对象
Person p=(Person) ioc.getBean("person2");
System.out.println(p);
}
利用p命名空间创建对象
首先在我们的xml文件的首部添上这句话:
xmlns:p="http://www.springframework.org/schema/p"
然后使用p标签:
<bean id="person3" class="helloWorld.Person" p:name="张三" p:age="17"></bean>
这样也可以创建对象。