作者:爱你一辈子2502860605 | 来源:互联网 | 2023-07-17 20:06
Spring框架XML配置文件使用外部Bean属性注入
- (1)创建两个类service类和dao类
- (2)在service中调用dao里面的方法
- (3)使用Spring框架进行调用
- (4)创建测试类
(1)创建两个类service类和dao类
创建UserService
类和UserDao
类,其中UserDao
为抽象类。对UserDao
进行重写UserDaoImpl
类。
1、UserService
类
package com.action.spring.service;import com.action.spring.dao.UserDao;
import com.action.spring.dao.UserDaoImpl;public class UserService {private UserDao userDao;public void setUserDao(UserDao userDao) {this.userDao = userDao;}public void add() throws Exception {System.out.println("Service add....................");userDao.update();}}
2、UserDao
类
package com.action.spring.dao;public interface UserDao {public abstract void update() throws Exception;}
3、UserDao
类的实现类UserDaoImpl
类
package com.action.spring.dao;public class UserDaoImpl implements UserDao{private String uname;public void setUname(String uname) {this.uname = uname;}@Overridepublic void update() throws Exception {System.out.println("update...............");}}
(2)在service中调用dao里面的方法
传统的调用方式为new
一个实现类实体,然后调用方法。
(3)使用Spring框架进行调用
配置XML
配置文件。
<beans xmlns&#61;"http://www.springframework.org/schema/beans"xmlns:xsi&#61;"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation&#61;"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id&#61;"userService" class&#61;"com.action.spring.service.UserService"><property name&#61;"userDao" ref&#61;"userDaoImpl">property>
bean>
<bean id&#61;"userDaoImpl" class&#61;"com.action.spring.dao.UserDaoImpl">bean>beans>
也是采用set
方法进行实例化操作。
所以在UserService
类中要创建一个属性&#xff0c;并创建set
方法用来控制属性。
在配置文件中实例化实现类&#xff1a;
然后实例化使用类&#xff1a;
此时通过注入外部Bean的方式注入属性。
其中name
为属性名。此处需要注意的是和普通值使用的value
不同的是&#xff0c;注入外部Bean需要使用 ref
属性。
&#xff08;4&#xff09;创建测试类
public class testSpring5 {&#64;Testpublic void testAdd() throws Exception {ApplicationContext context &#61;new FileSystemXmlApplicationContext("src/config/bean1.xml");UserService userService &#61; context.getBean("userService", UserService.class);userService.add();}}
文件的相对位置&#xff1a;
运行结果&#xff1a;