属性“dataSource”是必需的Java错误(Spring)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21671627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Property 'dataSource' is required Error in java (Spring)
提问by Mahi Mali
I am developing an web application in Java (Spring)
我正在用Java (Spring)开发一个 Web 应用程序
My java file is as,
我的java文件是,
try
{
JdbcTemplate jt = new JdbcTemplate(dataSource);
System.out.println("Connection ....."+jt.toString());
Connection conn;
Statement st;
conn =DriverManager.getConnection(jt.toString());
conn = (Connection) jt.getDataSource();
st=conn.createStatement();
System.out.println("Connection created....."+st);
}
catch (Exception e) {
System.out.println("Error Found...."+ e.getMessage());
System.out.println("Strack Trace....."+e.getStackTrace());
}
My spring-servlet.xmlfile is as,
我的spring-servlet.xml文件是这样的,
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/cjbranchdb" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource"><ref bean="dataSource"/></property>
</bean>
But it gets an error as,
但它得到一个错误,
Error Found: Property 'dataSource' is required.
Strack Trace: [Ljava.lang.StackTraceElement;@7948dd
Here, I want to make a connection in Java file and pass it to the another variable as Jasper Report.
在这里,我想在 Java 文件中建立连接并将其作为 Jasper Report 传递给另一个变量。
Please help, How to fix this issue?
请帮忙,如何解决这个问题?
采纳答案by Pavel Horal
I am guessing you are completely new to Java, JEE, Spring and JDBC. As I have stated in my comment, it is hard to answer your question, if what you are doing in there is incorrect in its base. I will try to go through few topics and hopefully also pin point where your current issue is.
我猜你对 Java、JEE、Spring 和 JDBC 完全陌生。正如我在评论中所述,如果您在其中所做的事情的基础不正确,则很难回答您的问题。我将尝试讨论几个主题,并希望也能指出您当前的问题所在。
Spring app structure
Spring应用程序结构
You need to be sure to correctly structure your project:
您需要确保正确构建您的项目:
src
main
java
- directory for Java sourcesin/mmali/springtest/controller/IndexController.java
- Your controller class
resources
- directory for non-Java (re)sourceswebapp
- root for the web application resourcesWEB-INF/web.xml
- JEE web application configurationWEB-INF/spring-servlet.xml
- application context configuration for dispatcher servlet
pom.xml
- Maven config (in case you are using Maven)
src
main
java
- Java 源目录in/mmali/springtest/controller/IndexController.java
- 你的控制器类
resources
- 非 Java(重新)源的目录webapp
- Web 应用程序资源的根目录WEB-INF/web.xml
- JEE Web 应用程序配置WEB-INF/spring-servlet.xml
- 调度程序 servlet 的应用程序上下文配置
pom.xml
- Maven 配置(如果您使用的是 Maven)
I would call this a common structure for Java project, mostly "standardized" by Maven.
我将其称为 Java 项目的通用结构,主要由 Maven 进行“标准化”。
Correct JEE config
正确的 JEE 配置
You need to have correct web.xml
configuration:
您需要有正确的web.xml
配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
This is a basic configuration (without root context), which will use your spring-servlet.xml
as Spring context configuration.
这是一个基本配置(没有根上下文),它将使用您spring-servlet.xml
作为 Spring 上下文配置。
Correct Spring configuration
正确的弹簧配置
You need to have correct Spring context configuration:
您需要有正确的 Spring 上下文配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<mvc:resources location="/resources/" mapping="/resources/**" />
<!-- With ROOT context we would restrict component scan on controllers here -->
<context:component-scan base-package="in.mmali.springtest" />
<!-- Data source configuration would normally go inside ROOT context. -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/cjbranchdb" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
This will load all classes annotated with @Component
(and its companions @Controller
, @Service
, @Repository
) as your beans. Beanin a context of Spring application is a object managed by Spring -> i.e. object which is being instantiated by Spring itself. When you want to work with a Spring bean, you need to have it injected (e.g. by using @Autowired
annotation) or you need to pull it out from ApplicationContext#getBean
manually.
这将加载所有用@Component
(及其同伴@Controller
, @Service
, @Repository
)注释的类作为您的 bean。Spring 应用程序上下文中的Bean是由 Spring 管理的对象 -> 即由 Spring 本身实例化的对象。当您想使用 Spring bean 时,您需要将它注入(例如通过使用@Autowired
注释),或者您需要ApplicationContext#getBean
手动将其拉出。
Working with JDBC
使用 JDBC
Working with JDBC is painful with all the closeableresources and checked exceptions. That is why Spring-JDBC project wraps JDBC API so you don't have to use it.
对于所有可关闭的资源和已检查的异常,使用 JDBC 是痛苦的。这就是为什么 Spring-JDBC 项目包装了 JDBC API 以便您不必使用它。
To showcase how you should work with JDBC and also how to let Spring inject dependencies, here is a simple controller:
为了展示您应该如何使用 JDBC 以及如何让 Spring 注入依赖项,这里有一个简单的控制器:
@Controller // Will be detected by <context:component-scan>
@RequestMapping // Will be detected by <mvc:annotation-driven> (more specifically by one of its component - RequestMappingHandlerMapping)
public class IndexController {
@Autowired // Spring will inject JdbcTemplate here
private JdbcOperations jdbcOperations;
@RequestMapping // This method should be called for requests to "/"
@ResponseBody // Returned string will be returned to client... normally you would register view resolver and just return name of a JSP to render
public String renderIndex() {
// You don't need to worry about JDBC's DataSource, Connection, ResultSet, ... just use JdbcTemplate
long rowCount = jdbcOperations.queryForLong("SELECT COUNT(*) FROM my_test_table;");
return "Number of rows in database is: " + String.valueOf(rowCount);
}
}
Note, that in a real application you would not allow controller to work with your data source directly, but rather through service and data layer.
请注意,在实际应用程序中,您不允许控制器直接使用您的数据源,而是通过服务和数据层。
Next steps
下一步
- Start using logging systemand never use
System.out.println
in a web application again ;). I suggest slf4jwith its simple binding for start (later you can configure it to use logbackor log4j). - Configure your application to use transactions. Use Spring's transaction handling (
<tx:annotation-driven/>
with@Transactional
). It might look as magic at first, but when you discover something about AOP and proxy classes, you will then start really appretiating the principles of how Spring works. - Split your application logicto service layer and data (DAO) layer.
- Check Spring's sample application(http://docs.spring.io/docs/petclinic.html) and reference application (https://github.com/spring-projects/greenhouse).
- 开始使用日志系统,再也不要
System.out.println
在 Web 应用程序中使用;)。我建议使用slf4j及其简单的启动绑定(稍后您可以将其配置为使用logback或log4j)。 - 配置您的应用程序以使用事务。使用 Spring 的事务处理(
<tx:annotation-driven/>
with@Transactional
)。起初它可能看起来很神奇,但是当您发现有关 AOP 和代理类的一些东西时,您就会开始真正了解 Spring 的工作原理。 - 将应用程序逻辑拆分为服务层和数据 (DAO) 层。
- 检查 Spring 的示例应用程序( http://docs.spring.io/docs/petclinic.html) 和参考应用程序 ( https://github.com/spring-projects/greenhouse)。
回答by Subin Sebastian
JdbcTemplate jt = new JdbcTemplate(dataSource);
You cant just use new
keyword to construct a bean object. Obviously the references in that object will be null.
JdbcTemplate jt = new JdbcTemplate(dataSource);
您不能仅使用new
关键字来构造 bean 对象。显然,该对象中的引用将为空。
Instead you should ask spring to give you that bean object. Some thing like this.
相反,您应该要求 spring 给您那个 bean 对象。像这样的东西。
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-servlet.xml");
JdbcTemplate jt = (JdbcTemplate)context.getBean("JdbcTemplate");
In this case spring will inject the dependency ie datasource
as given in configuration.
在这种情况下,spring 将注入依赖项,即datasource
配置中给出的。
回答by Stanley Stein
According to the file name, I assume you that you are building a web-based application.
根据文件名,我假设您正在构建基于 Web 的应用程序。
For capturing the error, please use a proper logging framework instead of System.out.println.
为了捕获错误,请使用适当的日志框架而不是 System.out.println。
According to the error, dataSource seems null. Please kindly check if your web.xmlhas defined the servlet xml file, such as
根据错误,dataSource 似乎为空。请检查您的web.xml是否定义了 servlet xml 文件,例如
<servlet>
<servlet-name>spring_app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
In addition, DriverManagerDataSource is good enough for testing only. For production use, please consider Apache's Jakarta Commons DBCP or C3P0. See detail at the official webpage.
此外,DriverManagerDataSource 仅用于测试就足够了。对于生产用途,请考虑 Apache 的 Jakarta Commons DBCP 或 C3P0。见细节在官方网页。
Since your XML file has mentioned
由于您的 XML 文件已经提到
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource"><ref bean="dataSource"/></property>
</bean>
, the XML file should consist of a servlet section to call the object of id=JdbcTemplate. For example,
,XML 文件应该包含一个 servlet 部分来调用 id=JdbcTemplate 的对象。例如,
<bean id="MyServlet" class="com.my.MyServlet">
<property name="jdbcTemplate"><ref bean="JdbcTemplate"/></property>
</bean>