到目前为止,我所走过的大多数教程都像这样从主类访问bean:
public class JdbcDemo {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
SimpleJdbcDaoImpl dao = ctx.getBean("simpleJdbcDaoImpl", SimpleJdbcDaoImpl.class);
System.out.println("Circle count from main class is: " + dao.getCircleCount());
}
}
和SimpleJdbcDaoImpl类:
public class SimpleJdbcDaoImpl extends SimpleJdbcDaoSupport {
public int getCircleCount() {
String sql = "SELECT COUNT(*) FROM CIRCLE";
return this.getJdbcTemplate().queryForInt(sql);
}
}
要通过从主类中调用该bean来访问它,我必须付出很多努力,例如:
主要类别:
public class JdbcDemo {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
System.out.println(ctx.getBean(SomeOtherClass.class).accessSimpleJdbcDaoImpl());
}
}
然后在其他
SomeOtherClass
类中:@Service
public class SomeOtherClass implements ApplicationContextAware {
private ApplicationContext ac;
public String accessSimpleJdbcDaoImpl() {
return "We're getting into some other secondary class.\n" + ac.getBean(SecondaryClass.class).printSecCount();
}
@Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
this.ac = ac;
}
}
然后在
SecondaryClass
@Service
public class SecondaryClass {
@Autowired
private SimpleJdbcDaoImpl simpleJdbcDaoImpl;
public String printSecCount() {
return "Secondary class Circle count is: " + simpleJdbcDaoImpl.getCircleCount();
}
}
这似乎使项目与Spring的联系过于紧密。另外,在我的项目中,有些类仅在某些类中需要,因此从主调用它们是没有必要的,或者就是行不通的。
有没有办法实现ApplicationContextAware而不是从主类调用它们?
更新:
如何从下面的SecondaryClass访问类
AwayTest.printAwayTest()
?@Component
public class AwayTest {
public String printAwayTest() {
return "Away here\n";
}
}
这什么也没有。
@Service
public class SecondaryClass {
@Autowired
private AwayTest awayTest;
private SimpleJdbcDaoImpl simpleJdbcDaoImpl;
@Autowired
public void setSimpleJdbcDaoImpl(SimpleJdbcDaoImpl impl) {
simpleJdbcDaoImpl = impl;
}
public String printSecCount() {
return "Away Test: " + awayTest.printAwayTest() + ". Secondary class Circle count is: " + simpleJdbcDaoImpl.getCircleCount();
}
}
最佳答案
只需为依赖项注入创建适当的setter。如果需要SimpleJdbcDaoImpl
的实例,则不应声明私有的自动装配字段。而是创建一个setter或构造函数参数。它将消除对使用反射设置字段的依赖。
@Service
public class SomeOtherClass {
private SecondaryClass secondary;
@Autowired
public void setSecondary(SecondaryClass secondary) {
this.secondary = secondary;
}
public String accessSimpleJdbcDaoImpl() {
return "We're at Some Other Class: " + secondary.printSecCount();
}
}
@Service
public class SecondaryClass {
private SimpleJdbcDaoImpl simpleJdbcDaoImpl;
@Autowired
public void setSimpleJdbcDaoImpl(SimpleJdbcDaoImpl impl) {
simpleJdbcDaoImpl = impl;
}
public String printSecCount() {
return "Secondary class Circle count is: " + simpleJdbcDaoImpl.getCircleCount();
}
}