一直以为抽象类既然不能被实例化,那么自然的,也就不能被spring管理,既然不能被spring管理,自然也就不能使用@Autowired或者@Resource来注入属性了,但是其实是可以的,这样子,当我们有公用的代码的时候就不需要再使用类似util的方式来实现,而是通过继承就行了。下面show you code。
一、配置一下spring扫描路径beans-abs.xml:
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.roadjava.test.spring.abs"/> </beans>
二、定义一个抽象类
package com.roadjava.test.spring.abs; import com.roadjava.test.spring.abs.svc.impl.GoodsServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Resource; public abstract class AbstractConsumer { // @Resource 两者都可以 @Autowired private GoodsServiceImpl goodsServiceImpl; public void handle(String str){ goodsServiceImpl.say(); } }
三、用到的GoodsServiceImpl:
package com.roadjava.test.spring.abs.svc.impl; import org.springframework.stereotype.Service; @Service public class GoodsServiceImpl { public void say(){ System.out.println(111111); } }
四、实现抽象类
package com.roadjava.test.spring.abs; import org.springframework.stereotype.Component; import java.util.List; @Component public class GoodsConsumer extends AbstractConsumer { public void consumers(List<String> list){ for (String str:list){ super.handle(str); } } }
五、测试:
@Test public void test5(){ ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("spring/beans-abs.xml"); GoodsConsumer bean = ac.getBean("goodsConsumer", GoodsConsumer.class); bean.consumers(Lists.newArrayList("a","b")); }
运行结果:
当然你也可以把在抽象类中要被注入的属性声明为protected的,这样在子类中也可以使用了。