spring快速入门(三)

时间:2023-03-08 16:57:51

一、在spring快速入门(二)的基础上,原先我们是采用构造方法完成对象的注入。这里还有其他的方法可以完成注入,通过set方法来完成。

  修改UserActionImpl

  

package com.murong.action;

import com.murong.dao.UserDao;
import com.murong.dao.UserDaoMysqlImpl;
import com.murong.dao.UserDaoOracleImpl; public class UserActionImpl implements UserAction{ private UserDao userDao; /*public UserActionImpl(UserDao userDao) {
this.userDao = userDao;
}*/
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} @Override
public void addUser(String name, int age) { userDao.addUser(name, age);
} }

  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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <bean id="userDaoMysqlImpl" class="com.murong.dao.UserDaoMysqlImpl"/> <bean id="userDaoOracleImpl" class="com.murong.dao.UserDaoOracleImpl"/> <bean id="userActionImpl" class="com.murong.action.UserActionImpl"> <!-- mysql的实现 -->
<!-- <constructor-arg ref="userDaoMysqlImpl"/> -->
<!-- oracle的实现 -->
<!-- <constructor-arg ref="userDaoOracleImpl"/> --> <property name="userDao" ref="userDaoMysqlImpl"/> </bean>
</beans>

 注意: <property name="userDao" ref="userDaoMysqlImpl"/>  中, name 的值 是set之后的方法名称,首字母小写。

  其他文件不改变、、、、、、

  可能会出现的问题: Could not instantiate bean class [com.murong.action.UserActionImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.murong.action.UserActionImpl.<init>()

  原因:如果通过set方法的实现,必须提供无参的构造方法。所以必须注释有参的构造函数。