I'm trying to implement a Spring MVC web-app (using Spring-FW-ver: 4.3.1). And my web-app's DAO layer architecture is as follows :-
//1. BaseDAO interface
public interface BaseDAO {
//abstract methods
}
//2. BaseDAOJdbcImpl.java file - an abstract DAO class for common method(s) which other sub-DAO classes can inherit
#Repository
public abstract class BaseDAOJdbcImpl extends NamedParameterJdbcDaoSupport implements BaseDAO
{
// implementations of above BaseDAO abstract methods
}
//3. UserDAO interface that extends BaseDAO interface
public interface UserDAO extends BaseDAO {
//abstract methods for User
}
//4. UserDAOJdbcImpl.java class file
#Repository
public class UserDAOJdbcImpl extends BaseDAOJdbcImpl implements UserDAO
{
// implementations of above UserDAO abstract methods
}
And the webapp-servlet.xml Spring-MVC config file :-
.
.
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="springcrud"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/pmsDS"/>
</bean>
<bean id="baseDAOJdbcImpl" class="springcrud.dao.BaseDAOJdbcImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
.
.
I'm getting the following error :-
java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
The dataSource object is not being injected into DAO layer. Is the above DAO layer architecture valid or is it a problem with Spring configuration?
Related
I have my datasource in below class. Is there any way I can use that in config.xml?
I am getting an Error creating bean with name 'cmsTemplate' defined in file: cannot resolve reference bean 'contentDataSource' while setting constructor argument.
JdbcConfiguration.java
#Configuration
public class JdbcConfiguration{
#Value("$comContent.url")
private String dbUrl;
#Value("$comContent.dbUser")
private String dbUser;
#Value("$comContent.dbPass")
private String dbPass;
//rest of the properties
#Bean
#Primary
public DataSource contentDataSource() throws SQLException {
//code
}
}
config.xml
<bean id="cmsTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-args type="javax.sql.DataSource">
<ref bean="contentDataSource"/>
</constructor-args>
<property name="fetchSize" value="{systemProperties['jdbcFetchSize']}" />
</bean>
//Need to create datasource before spring context is getting created. Previously it was like below commented code.
<!-- <bean id="contentDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/comContent</value>
</property>
</bean> -->
I´m rewriting a spring context from xml to java class but I don´t know this part:
<interceptors>
<interceptor>
<mapping path="/index.html"/>
<beans:bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<beans:property name="cacheSeconds" value="0"/>
<beans:property name="useExpiresHeader" value="true"/>
<beans:property name="useCacheControlHeader" value="true"/>
<beans:property name="useCacheControlNoStore" value="true"/>
</beans:bean>
</interceptor>
</interceptors>
I have rewritten this but the interceptors and mapping tags I don´t know:
#Bean
public WebContentInterceptor webContentInterceptor() {
WebContentInterceptor webContentInterceptor = new WebContentInterceptor();
webContentInterceptor.setCacheSeconds(0);
webContentInterceptor.setUseExpiresHeader(true);
webContentInterceptor.setUseCacheControlHeader(true);
webContentInterceptor.setUseCacheControlNoStore(true);
return webContentInterceptor;
}
Assuming you have a class like WebConfig where you have added #EnableWebMvc, modify it to something like the following:
#EnableWebMvc
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addInterceptors(InterceptorRegistry registry) {
final WebContentInterceptor webContentInterceptor = new WebContentInterceptor();
//the rest of the initialization here
registry.addInterceptor(webContentInterceptor).addPathPatterns("/index.html);
}
}
I was trying to access database using jdbcdao as per the following example:
http://www.mkyong.com/spring/spring-jdbctemplate-jdbcdaosupport-examples/
userdao, userdaoimpl,daocontext and datacontext.xml are as follows:
DAOIMPL
public class UserDAOImpl extends JdbcDaoSupport implements UserDAO {
/*Creates User */
public void insertUser(User user){
String sql = "INSERT INTO Users " +
"(id, username, password,role) VALUES (?, ?, ?,?)";
getJdbcTemplate().update(sql, new Object[] { user.getUserId(),
user.getUserName(),user.getPassWord()
});
}
}
DAO
import java.util.List;
import spring.web.models.User;
public interface UserDAO {
public void insertUser(User user);
}
DAOCONTEXT.XML
<beans xmlns="http://www.springframework.org/schema/beans"
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-4.0.xsd">
<bean id="userDAO" class="spring.web.dao.impl.UserDAOImpl">
<property name="primaryDataSource" ref="oracleDataSource" />
</bean>
</beans>
DATA-CONTEXT.XML
<?xml version="1.0"?>
<beans
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans">
<bean id="oracleDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property value="oracle.jdbc.OracleDriver" name="driverClassName" />
<property value="jdbc:oracle:thin:#192.168.72.68:1521:d2he"
name="url" />
<property value="aaryal_1" name="username" />
<property value="oracle" name="password" />
</bean>
</beans>
The error I am facing is as follows:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO' defined in class path resource [dao-context.xml]:
Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException:
Invalid property 'primaryDataSource' of bean class [spring.web.dao.impl.UserDAOImpl]:
Bean property 'primaryDataSource' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?
Please suggest me what did I miss.
You need a setPrimaryDataSource method in UserDAOImpl class. The error says it all. It's expecting a property called primaryDataSource in your class, but can't find it. Hence the error.
You'll need to do this:
private DataSource dataSource;
public void setPrimaryDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
EDIT:
If you go through the API of JdbcDaoSupport, the setDataSource method already exists. So to solve your error, you can either do the above, or simply rename your DataSource bean name to dataSource
I am trying to use custom validation error messages by using properties file. I have placed messages.properties file in web content/web-inf/ folder.
NonEmpty.batchDomain.batchName=Invalid message 2.
My applicationContext file is :
<context:component-scan base-package="com.coaching.controller" />
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views
directory -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
And my controller is :
#RequestMapping(method = RequestMethod.POST)
public ModelAndView addBatch(
#Valid #ModelAttribute("batchDomain") BatchDomain batchDomain,
BindingResult result, HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
if (result.hasErrors()) {
ModelAndView modelAndView = new ModelAndView("newBatch");
return modelAndView;
}
}
BatchDomain is :
public class BatchDomain {
#NotNull
#NotEmpty
#Size(min = 1, max = 100)
private String batchName;
#Min(1)
#Max(1000)
private int strength;
}
As far as I have seen in google, I am following the correct approach. So, what can be the reason behind this issue?
You may try to put file "messages.properties" in /src/main/resource directory.
i have a problem with spring mvc
my spring bean
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" 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-2.5.xsd">
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="welcome.htm">welcomeController</prop>
</props>
</property>
</bean>
<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>
<bean name="welcomeController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="welcome" />
<bean name="/bscList.htm" class="cbs.web.BscController">
<property name="bscDao" ref="myBscDao" />
</bean>
<bean name="/bscForm.htm" class="cbs.web.BscFormController">
<property name="commandName" value="bsc"/>
<property name="commandClass" value="cbs.domain.Bsc"/>
<property name="formView" value="bscForm"/>
<property name="successView" value="bscList.htm"/>
<property name="bscDao" ref="myBscDao"/>
</bean>
</beans>
my form controller
public class BscFormController extends SimpleFormController {
private static Logger log = Logger.getLogger(BscController.class);
private BscDao bscDao;
public void setBscDao(BscDao bscDao) {
this.bscDao = bscDao;
}
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
String id = request.getParameter("id");
if (!StringUtils.isBlank(id)) {
return bscDao.get(new Integer(id));
}
return new Bsc();
}
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
log.debug("entering 'onSubmit' method...");
Bsc bsc = (Bsc) command;
String success = getSuccessView();
if (request.getParameter("delete") != null) {
bscDao.remove(bsc.getId());
} else {
bscDao.save(bsc);
}
return new ModelAndView(success);
}
}
my problem:
when I access /bscList.htm, it's display list of bsc (bscList.jsp template),
but when I access /bscForm.htm, it's still display bsc's list, not show my form (bscForm.jsp template)
I have test with some simple controller:
controller implement org.springframework.web.servlet.mvc.Controller, evething run fine
controller extends SimpleFormController, map error:
No mapping found for HTTP request with URI [/cbs/testform.htm] in DispatcherServlet with name 'dispatcher'
when i use HandlerMapping ControllerClassNameHandlerMapping, all request URL '/bsc*' will map to BscController (/bscForm.htm will not map to BscFormController)