<bean id="userAction" class="com.umgsai.spring.UserAction"> <property name="userManager" ref="manager"></property><!-- 依赖注入 --> </bean> <bean id="manager" class="com.umgsai.spring.UserManager"> <property name="driverClass"> <value>com.microsoft.sqlserver.jdbc.SQLServerDriver</value> </property> <property name="username"> <value>sa</value> </property> <property name="password"> <value>123456</value> </property> <property name="url"> <value>jdbc:sqlserver://localhost:1433;database=surveillance</value> </property> </bean>
UserManager.java
package com.umgsai.spring; public class UserManager { private String username; private String password; private String url; private String driverClass; public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setUrl(String url) { this.url = url; } public void setDriverClass(String driverClass) { this.driverClass = driverClass; } public void add(User user) { System.out.println(username); System.out.println(password); System.out.println(driverClass); System.out.println(url); System.out.println("执行添加User操作"); } }
UserAction.java
package com.umgsai.spring; public class UserAction { private UserManager userManager; public void setUserManager(UserManager userManager) { this.userManager = userManager; } public String execute() { User user = new User(); userManager.add(user); return "success"; } }
public static void main(String[] args) { //IMessage message = MessageFactory.create("1"); //创建spring Bean工厂 BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); //BeanFactory factory = new ClassPathXmlApplicationContext("app*.xml");通配符 UserAction userAction = (UserAction)factory.getBean("userAction"); System.out.println(userAction.execute()); }
控制台输出
sa
123456
com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc:sqlserver://localhost:1433;database=surveillance
执行添加User操作
success