一、spring对象的获取
1.通过配置文件中的id获取IOC容器中的对象
配置文件(IOC容器) ioc.xml
<?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="person" class="com.lxg.HelloSpring.Person">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="18"></property>
<property name="gender" value="男"></property>
</bean>
</beans>
测试例子 MyTest.java
package com.lxg.springIOC.test;
import com.lxg.springIOC.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.swing.*;
public class MyTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = (Person) applicationContext.getBean("person");
Person person1 = applicationContext.getBean("person",Person.class);
System.out.println(person);
System.out.println(person1);
}
}
2.通过bean的类型获取对象
package com.lxg.springIOC.test;
import com.lxg.springIOC.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.swing.*;
public class MyTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person2 = applicationContext.getBean(Person.class);
System.out.println(person2);
}
}
**注意:**通过bean的类型查找对象的时候,在配置文件中不能存在两个类型一致的bean对象,如果有的话,可以通过如下方法:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
Person person = context.getBean("person", Person.class);
System.out.println(person);
}
}
|