标签:bean 泛型 autowire java rac 五步 xtend log turn
废话不多说,直接上代码
一.写一个实体类
package generic; import java.io.Serializable; public class User implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
二.公共DAO:BaseDao(crud都写在这里)
package generic; public abstract class BaseDao<T> { public void save(T t){ System.out.println("....."); } public void delete(){ System.out.println("...."); } }
三.DAO的具体实现:UserDa继承BaseDao
package generic; import org.springframework.stereotype.Repository; @Repository("userDao") public class UserDao extends BaseDao<User>{ }
四.公共Service:BaseService(这里写一些公共方法和一个抽象方法,抽象方法为了获取BaseService的具体实现)
package generic; public abstract class BaseService<T> { public abstract BaseDao<T> getBaseDao(); public void save(T t){ getBaseDao().save(t); } }
五.写BaseService的具体实现:UserService并继承BaseService
package generic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("userService") public class UserService extends BaseService<User>{ @Autowired private UserDao userDao; @Override public BaseDao<User> getBaseDao() { return userDao; } }
其中第四步和第五步是以前的写法,Spring4的新泻法如下:
新四:
package generic; import org.springframework.beans.factory.annotation.Autowired; public abstract class BaseService<T> { @Autowired private BaseDao<T> baseDao; public void save(T t){ baseDao.save(t); } }
新五:
package generic; import org.springframework.stereotype.Service; @Service("userService") public class UserService extends BaseService<User>{ }
大家可以看到现在的代码非常简洁,在步骤新四中,注入的时候spring会去自动去找BaseDao<User>的子类实现并注入
标签:bean 泛型 autowire java rac 五步 xtend log turn
原文地址:http://www.cnblogs.com/shaoyang/p/6860364.html