我正在尝试解决一个非常简单的解决方案:
我有我的 DAO 对象:
package com.me.dao;
@Service
public class JavaNeo4jConnection implements Neo4jConnection {
private JdbcTemplate jdbcTemplate;
@Autowired(required = true)
private DriverManagerDataSource dataSource;
public void setDataSource(DriverManagerDataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
}
我已经在 springConfig.xml 中声明了数据源
<context:annotation-config />
<context:component-scan base-package="com.me.dao" />
<context:component-scan base-package="com.me.servlets" />
<!-- Servlet -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- dataSource bean-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.neo4j.jdbc.Driver" />
<property name="url" value="${neo4j.dburl}" />
<property name="username" value="${neo4j.username}" />
<property name="password" value="${neo4j.password}" />
</bean>
<!-- Config properties file-->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
</bean>
dao 对象正在使用我的 servlet Controller 中的 Autowiring 进行实例化:
package com.me.servlets;
@Controller
public class JsonServer {
@Autowired
Neo4jConnection neoConn;
@RequestMapping("/servejson")
@ResponseBody
public void serveJson(HttpServletRequest request, HttpServletResponse response
) throws IOException {
OutputStream os = response.getOutputStream();
String json = neoConn.getInfo(request.getParameter("query"));
os.write(json.getBytes());
os.close();
os.flush();
}
}
但是 dataSource 从未实例化,运行我的代码将产生 NullPointerException
。
我在这里缺少什么?我相当确定我误用了 @Autowired
。
最佳答案
给定
@Service
public class JavaNeo4jConnection implements Neo4jConnection {
和
<context:component-scan ... />
// or <context:annotation-config /> which is redundant if you have the 'component-scan'
Spring 将实例化您的 JavaNeo4jConnection
bean。在此过程中,它将扫描类的成员以查找 @Autowired
(以及其他内容)。如果它发现一个用它注释的字段,它将尝试解析一个 bean 并注入(inject)它。如果它找到用它注释的方法,它将查看参数并尝试解析适当的 bean 并在调用该方法时将它们用作参数。
因为您只有一个带注释的字段
@Autowired
Neo4jConnection neoConn;
Spring将直接使用字段注入(inject)。它会将找到的 bean 分配给该字段。它不会调用您的 setter 方法,因此不会初始化 JdbcTemplate
字段。
一种解决方案是将注释移至setter方法(方法注入(inject))。
另一个使用字段注入(inject)的解决方案是用 @PostConstruct
带注释的方法替换 setter 方法
@PostConstruct
public void init() {
// dataSource has been injected
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
或者使用构造函数注入(inject)
@Autowired
public JavaNeo4jConnection(DriverManagerDataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
关于java - 如何实例化在 spring 配置中声明为 bean 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31150311/