自定义的依赖注入[Action层/Service层/DAO层分离 , 解耦]
工具类:
1. ServiceProvinderCore.java
package cn.itcast.crm.container; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 提供service的容器, 这里自定义一个容器, 和action分离, 达到解耦的目的 */ public class ServiceProvinderCore { protected ApplicationContext ctx; /** * @param filename beans.xml */ public void load(String filename) { ctx = new ClassPathXmlApplicationContext(filename); } }
2. ServiceProvinder.java
package cn.itcast.crm.container; import org.apache.commons.lang.StringUtils; /** * 该类的主要作用的是加载beans.xml文件 */ public class ServiceProvinder { private static ServiceProvinderCore sc; static { sc = new ServiceProvinderCore(); sc.load("beans.xml"); } public static Object getService(String beanName) { if (StringUtils.isBlank(beanName)) { throw new RuntimeException("您要访问的服务名称不能为空"); } Object bean = null; // 如果spring容器中包含beanName if (sc.ctx.containsBean(beanName)) { bean = sc.ctx.getBean(beanName); } // 如果spring容器不包含beanName if (bean == null) { throw new RuntimeException("您要访问的服务名称[ " + beanName + " ]不存在"); } return bean; } }
3. 使用:
(1) 在接口中声明全局常量, 包.类的形式
ISysUserService.java
public interface ISysUserService {
public static final String SERVER_NAME = "cn.itcast.crm.service.impl.SysUserServiceImpl";
}
(2) 在接口实现类中加上注解@XXXX
SysUserServiceImpl.java
@Service(ISysUserService.SERVER_NAME)
public class SysUserServiceImpl implements ISysUserService {
// 这里按照service的注入方法注入dao(dao接口和实现类写法和service一样)
}
(3) 在action中按下形式注入service
SysUserAction.java
public class SysUserAction extends BaseAction {
// 注入service
private ISysUserService sysUserService = (ISysUserService) ServiceProvinder.getService(ISysUserService.SERVER_NAME);
}