一、基础配置
1、导入Spring依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
2、写一个简单的实体类Person,包含name和age两个字段,并提供set/get方法和构造方法。
3、 编写Spring的配置文件SpringConfig.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">
</beans>
二、Bean的注入
1、通过set方法注入bean,需要在配置文件中配置bean。其中bean标签中 id代表bean的id,class是要注入实体的实体类,property表示注入的属性。需要注意的是,要在Person类中提供set方法才可以注入成功。
<?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="Dao" class="com.fbd.pojo.Person">
<property name="name" value="张三"></property>
<property name="age" value="10"></property>
</bean>
</beans>
2、通过构造方法注入,使用此方式注入bean需要在Person类中提供构造方法。如果按照构造方法参数的顺序注入,可以不用写index。
<bean id="Dao" class="com.fbd.pojo.Person">
<constructor-arg index="0" value="李四"/>
<constructor-arg index="1" value="12"/>
</bean>
三、获取bean
public static void main(String[] args) {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("SpringConfig.xml");
Object dao = context.getBean("Dao");
System.out.println(dao);
}
编写一个测试类,创建ClassPathXmlApplicationContext对象,通过getBean方法获取bean,
getBean()方法中可以传入bean的id,即通过bean的名称获取bean,也可以通过bean的类型获取bean,例如:
Person bean = context.getBean(Person.class);
要注意,通过类型注入,不能写两个同类型的bean,否则会报异常。比如:
<bean id="Dao1" class="com.fbd.pojo.Person">
<constructor-arg type="java.lang.String" index="0" value="李四"/>
<constructor-arg type="int" index="1" value="12"/>
</bean>
<bean id="Dao2" class="com.fbd.pojo.Person">
<property name="age" value="12"></property>
<property name="name" value="张三"></property>
</bean>
上面在配置文件中写了两个bean,都是Person类的,尝试通过类型获取bean。抛出以下异常:
可以使用bean名称获取bean,解决这类的异常。