配置文件格式:
<?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="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here --> </beans>
引入配置文件:
ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
构造2个bean 进行注入:
<bean name="u" class="com.sfwl.DAO.impl.UserDAOImpl"> </bean> <bean name="service" class="com.sfwl.service.UserService"> <!-- SET注入 方法(主要)--> <property name="userDao" ref="u" /> <!-- 构造注入 需要有构造 方法--> <constructor-arg> <ref bean="u"/> </constructor-arg> </bean>
调用:
UserService service=cxt.getBean("service",UserService.class); User user=new User(); service.UserSava(user);