spring针对抽象类注入属性
一直以为抽象类既然不能被实例化,那么自然的,也就不能被spring管理,既然不能被spring管理,自然也就不能使用@Autowired或者@Resource来注入属性了,但是其实是可以的,这样子,当我们有公用的代码的时候就不需要再使用类似util的方式来实现,而是通过继承就行了。下面show you code。一、配置一下spring扫描路径beans-abs.xml...
·
一直以为抽象类既然不能被实例化,那么自然的,也就不能被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的,这样在子类中也可以使用了。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)