java抽象类注⼊_如何在抽象类中注⼊bean
抽象类是⽆法实例化的,因此⽆法使⽤@Service等这种注解直接将抽象类交给ioc容器管理,但是项⽬中往往需要有很多⼦类公⽤抽象⽗类
的模板⽅法,那么怎么实现呢?
错误演⽰
1、抽象类
@Componentpublic abstract classBaseService {
@Autowired
Dao dao;
}
2、⼦类
@Componentpublic class MyService extendsBaseService{public voidprint(){//运⾏时为null
System.out.String());
}
}
在我们实例化⼦类对象的时候,抽象⽗类不能实例化,因为spring注⼊的是实例对象,⽽不是类,所以spring不会将dao⾃动装配注⼊到⼀
个实例中。
解决⽅法
⼀、使⽤ApplicationContextAware
1、⼯程图
jar包只需要引⼊spring-context即可。
2、ApplicationContextUtil
packagespring.chapter1.utils;importorg.springframework.beans.BeansException;t.Applicatio
@Componentpublic class ApplicationContextUtil implementsApplicationContextAware {private staticApplicationContext applicationContext;
@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throwsBeansException {
ApplicationContextUtil.applicationContext=applicationContext;
}public staticObject getObject(String id) {
Object object= null;
Bean(id);returnobject;
}public staticApplicationContext getSpringContext() {returnapplicationContext;
}
}
3、抽象类
packagespring.chapter1.service;importspring.chapter1.dao.Dao;importspring.chapter1.utils.ApplicationContextUtil;public abstract classBaseService {
Dao dao;publicBaseService() {this.dao = (Dao) Object("dao");
}
}
4、⼦类
packagespring.chapter1.service;t.annotation.DependsOn;importorg.springframework.stereot
@Component/*** 因为BaseService中构造器需要使⽤applicationContextUtil这个bean,所以需要加@DependsOn这个注解。
*注解作⽤:1、保证applicationContextUtil总是在MyService之前实例化
* 2、保证applicationContextUtil总是在MyService销毁之后销毁*/@DependsOn("applicationContextUtil")public class MyService extendsBaseService{publicMyService() {super();
}public voidprint(){ dao.process();
}
}
5、Dao(⼀个demo组件,模拟调⽤某个bean的⽅法⽽已)
package spring.chapter1.dao;
import org.springframework.stereotype.Component;
@Component
public class Dao {
public void process() {
System.out.println("抽象⽗类中成功注⼊dao");
}
}
6、bean配置类(定义bean扫描策略)
fig;t.annotation.ComponentScan;
@Configuration
@ComponentScan(value= "spring.chapter1")public classBeanConfig {
}
7、测试类
packagespring.chapter1.main;importorg.junit.Test;t.annotation.AnnotationConfigApplication classSpringMain {
@Testpublic voidtest() {
AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(BeanConfig.class);
MyService myService= (MyService) Bean("myService");
myService.print();spring ioc注解
}
}
运⾏结果:
⼆、⼦类bean为⽗类注⼊bean
1、抽象类
public abstract classBaseService {
Dao dao;
}
2、⼦类
@Componentpublic class myService extendsBaseService{//Autowired修饰⽅法时,根据⽅法参数类型判断实例化哪个类
@Autowiredpublic voidprintDao(Dao dao){super.dao = dao;//⽗类属性注⼊
}public voidprint(){
System.out.String());
}
}
通过这种⽅式,抽象类就可以获取到bean,并进⾏使⽤了。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论