spring抽象类中注入bean
在使用spring的时候,有时由于设计的需要,需要使用抽象类(比如模板方法模式),但在抽象类中实现方法是需要依赖其他的接口或类的方法,这时就需要对依赖的接口或类进行注入,需要注意以下内容:
在抽象类中需要注入(@autowire),在继承了该抽象类的子类中同样需要再次注入。比如当前项目中,用户购买物品的模板抽象类中需要使用userservice,则在改抽象类中和道具服务类(实现了道具接口并继承了模板抽象类)均需要对userservice进行注入
当有多个子类的时候只要有一个子类中有注入实现,其他子类是不需要注入了可以直接使用:
public abstract class AbstractTest { @Autowired protected TusersMapper tusersMapper; }
//实现1 @Service public class AbstractTestImpl2 extends AbstractTest { public void test2(){ System.out.println(tusersMapper+"fsafdsafdsafsadfasf"); } }
//实现2 @Service public class AbstractTestImpl1 extends AbstractTest { @Autowired private TusersMapper tusersMapper; public void test1(){ System.out.println(tusersMapper+"fsafdsafdsafsadfasf"); } }
//测试 @Autowired AbstractTestImpl1 abstractTestImpl1; @Autowired AbstractTestImpl2 abstractTestImpl2; @Test public void test2(){ abstractTestImpl1.test1(); abstractTestImpl2.test2(); }
结果: