spring泛型依赖注入

1、spring依赖注入原理:

泛型依赖注入:子类之间的依赖关系由其父类泛型以及父类之间的依赖关系来确定,父类的泛型必须为同一类型。

通俗一点来说:两个子类之间的依赖关系不需要在子类中去声明,而是在父类中进行了声明,而依赖的纽带就是 泛型类型,必须是相同的父类泛型类型才具有依赖关系。

2、UML 类图

说明:在 BaseService 中通过 @Autowired 注解自动装配了 BaseDao 的实例。而在 UserService 中并没有注入 UserDao 的实例,但是通过父类的泛型类型,

在 UserService 中已经注入了 UserDao 的实例

package com.beans2.dao;

public class BaseDao<T> {

	
}

  

package com.beans2.service;

import org.springframework.beans.factory.annotation.Autowired;
import com.beans2.dao.BaseDao;

public class BaseService<T> {
	@Autowired
	private BaseDao<T> baseDao;
	public void add(){
		System.out.println("service add");
		System.out.println(baseDao);
	}

}

  

package com.beans2.dao;

import org.springframework.stereotype.Repository;

import com.beans2.model.User;
@Repository
public class UserDao extends BaseDao<User> {

}

  

package com.beans2.dao;

import org.springframework.stereotype.Repository;

import com.beans2.model.Type;

@Repository
public class TypeDao extends BaseDao<Type> {

}

  

package com.beans2.service;

import org.springframework.stereotype.Service;

import com.beans2.model.Type;

@Service
public class TypeService extends BaseService<Type> {

}

  

package com.beans2.service;

import org.springframework.stereotype.Service;

import com.beans2.model.User;

@Service
public class UserService extends BaseService<User> {

}

  

package com.beans2.model;

import java.sql.SQLException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.beans2.service.TypeService;
import com.beans2.service.UserService;

public class Main {

	public static void main(String[] args) throws SQLException{
		ApplicationContext context =
				new  ClassPathXmlApplicationContext("applicationContext2.xml");		
		
		UserService userService = (UserService) context.getBean("userService");
		userService.add();
		
		TypeService typeService = (TypeService) context.getBean("typeService");
		typeService.add();
		/*userDao 的bean
		 *userService的bean
		 * 
		 * */
	}

}

  

package com.beans2.model;

public class Type {

}

  

package com.beans2.model;

public class User {

}

  

控制台输出:

service add
com.beans2.dao.UserDao@7a30d1e6
service add
com.beans2.dao.TypeDao@5891e32e

 另附http://jinnianshilongnian.iteye.com/blog/1989330

posted @ 2018-09-14 17:01  南山湖畔  阅读(932)  评论(0)    收藏  举报