如何使用@Autowired而不是手动加载Spring bean?
问题描述:
我有一个连接到MySQL数据库的小型Java应用程序。对于数据库连接只有,我想用Spring来管理基于JNDI的连接池。如何使用@Autowired而不是手动加载Spring bean?
我有一个工作实现上述,但这需要手动加载JNDI连接bean,而我想使用@Autowired。
如何将我的工作代码转换为使用@Autowired
获取JNDI连接的工作代码?
这是我的beans.xml文件(里面的src/main/resources文件夹):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns= ....>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/Database"/>
</bean>
<bean id="databaseMapper2Impl"
class="com.dataaccess.DatabaseMapper2Impl">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
的是我DatabaseMapper2Impl
类的部分:
public class DatabaseMapper2Impl {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public OrderDTO getOrder(String orderNumber, String envToUse) {
String getOrderSql = "SELECT * FROM REPORTING.ORDER where ORDER_NUMBER = ? limit 1";
List<OrderDTO> orders = jdbcTemplateObject.query(getOrderSql, new Object[] { orderNumber }, new OrderMapper());
if (orders == null || orders.isEmpty()) {
return null;
} else {
return orders.get(0);
}
}
}
这是类哪里JNDI连接bean被手动实例化:
public class DataDelegateImpl {
public OrderDTO getOrder(String orderNumber, String envToUse) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
DatabaseMapper2Impl x = (DatabaseMapper2Impl) context.getBean("databaseMapper2Impl");
return x.getOrder(orderNumber, envToUse);
}
}
答
为了让春天到人年龄为DatabaseMapper2Impl
bean的实例化和注入时,您必须创建ApplicationContext
,并在该上下文中声明bean,完全如您所做。
如果问题只是如何避免使用XML为声明,你可以注释DatabaseMapper2Impl
与@Component
,而使用
ApplicationContext context = new AnnotationConfigApplicationContext(DatabaseMapper2Impl.class);
创建上下文。
如果你真的需要有DatabaseMapper2Impl
@Autowired
成DataDelegateImpl
一个实例,则该实例也将不得不由Spring来控制,所以你必须建立在较高水平的背景下,使DataDelegateImpl
豆以及。
您对此服务使用哪些注释? Spring看起来并不像这些bean是基于你在那里发现的。 – Makoto
不使用任何注释。 Bean正在使用:'ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”)'; – Ahmad