applicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!--打开注解开关--> <context:annotation-config/> <bean id="userAction" class="com.umgsai.spring.UserAction" scope="singleton"/> <bean id="userManager" class="com.umgsai.spring.UserManager" scope="prototype"> <property name="username" value="root"> </property> <property name="password" value="123456"> </property> <property name="url" value="jdbc:mysql://localhost:8080/3305"> </property> <property name="driverClass" value="jdbc.mysql.Driver"> </property> </bean> </beans>
package com.umgsai.spring; import javax.annotation.Resource; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; public class UserAction implements BeanFactoryAware{ @Resource//省略set方法 private UserManager userManager = null; public UserAction(UserManager userManager){ super(); this.userManager = userManager; } public UserAction(){ super(); } public String execute() { User user = new User(); //userManager = (UserManager)factory.getBean("manager"); userManager.add(user); System.out.println("userManager:"+userManager); return "success"; } private BeanFactory factory = null; public void setBeanFactory(BeanFactory factory) throws BeansException { this.factory = factory; } }
测试
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); UserAction userAction = (UserAction)factory.getBean("userAction"); System.out.println(userAction.execute());
执行结果
root
123456
jdbc.mysql.Driver
jdbc:mysql://localhost:8080/3305
添加User操作
userManager:com.umgsai.spring.UserManager@177ba38f
success
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1256242