新建Java项目,配置好spring环境。依赖注入有基于set方法的注入,基于构造方法的注入和接口注入三种。下面介绍前两种依赖注入。
基于Set方法的配置:
D层实现类:
<span style="font-size:18px;">package com.spring.dao;
public class UserDaoImpl implements UserDao {
@Override
public void addUser() {
System.out.println("addUser");
}
}
</span>
Service层的实现类:
<span style="font-size:18px;">public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void addUser() {
userDao.addUser();
}
}</span>
Client端:
<span style="font-size:18px;">public class Client {
public static void main(String[] args) {
BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService=(UserService)factory.getBean("userService");
userService.addUser();
}
}
</span>
配置文件application.xml:
<span style="font-size:18px;"><?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="userDao" class="com.spring.dao.UserDaoImpl"></bean>
<bean id="userService" class="com.spring.service.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
</span>
基于构造方法的配置:
构造方法与set方法的不同处有:
Service层的实现类:
<span style="font-size:18px;">public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void addUser() {
userDao.addUser();
}
}
</span>
配置文件application.xml:
<span style="font-size:18px;"><?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="userDao" class="com.spring.dao.UserDaoImpl"></bean>
<bean id="userService" class="com.spring.service.UserServiceImpl">
<constructor-arg ref="userDao"></constructor-arg>
</bean>
</beans>
</span>