How can i configure my spring aop xml with aop.xml an load time weaving? - spring

I have one "Hello word" application on spring AOP and configured by XML, it looks like this:
public class CustomerBoImpl {
public CustomerBoImpl() {
super();
}
protected void addCustomer(){
System.out.println("addCustomer() is running ");
}
}
public class App {
public static void main(String[] args) throws Exception {
ApplicationContext appContext =
new ClassPathXmlApplicationContext("Spring-Customer.xml");
CustomerBoImpl customer =
(CustomerBoImpl) appContext.getBean("customerBo");
customer.addCustomer();
}
}
My spring configuration looks like this:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:aspectj-autoproxy />
<!-- this switches on the load-time weaving -->
<context:load-time-weaver aspectj-weaving="on" />
<bean id="customerBo" class="com.mkyong.saad.CustomerBoImpl"
scope="singleton" />
<!-- Aspect -->
<bean id="logAspect" class="com.mkyong.saad.LoggingAspect" />
<aop:config>
<aop:aspect id="aspectLoggging" ref="logAspect">
<!-- #Before -->
<aop:pointcut id="pointCutBefore"
expression="execution(* com.mkyong.saad.CustomerBoImpl.addCustomer(..))" />
<aop:before method="logBefore" pointcut-ref="pointCutBefore" />
<!-- #After -->
<aop:pointcut id="pointCutAfter"
expression="execution(* com.mkyong.saad.CustomerBoImpl.addCustomer(..))" />
<aop:after method="logAfter" pointcut-ref="pointCutAfter" />
</aop:aspect>
</aop:config>
that doesn't work because of protected method, so I tried to use load time weaving with aop.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<aspectj>
<weaver>
<!-- only weave classes in our application-specific packages -->
<include within="com.mkyong.saad.*"/>
</weaver>
<aspects>
<!-- weave in just this aspect -->
<aspect name="com.mkyong.saad.LoggingAspect"/>
</aspects>
</aspectj>
Source code for the aspect:
public class LoggingAspect {
public void logBefore(JoinPoint joinPoint) {
System.out.println("logBefore() is running!");
System.out.println("hijacked : " + joinPoint.getSignature().getName());
System.out.println("******");
}
public void logAfter(JoinPoint joinPoint) {
System.out.println("logAfter() is running!");
System.out.println("hijacked : " + joinPoint.getSignature().getName());
System.out.println("******");
}
}
but it doesn't work, only if I change to annotation config. SOS PLZ

removing the following code in your aop.xml, then run your jvm with args like this: -javaagent:"yourpath/spring-instrument-***.jar"
<weaver>
<!-- only weave classes in our application-specific packages -->
<include within="com.mkyong.saad.*"/>
</weaver>

Related

How to build project by Spring Boot + Mybatis + Mybatis Generator?

I follow mybatis official website to build my project step by step, but it always can not work well, so I hope you could give me a fully guide from beginning to the end, many thanks.
Step 1. Build a new spring boot project named booking.
This step is basically, I will skip it.
Step 2. Add mybatis-generator to project.
This could help us to generate entity and mapper class mybatis needed automatically, it's very useful for us to save our time.
Add plugin config in pom.xml
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
</plugin>
Create generatorConfig.xml at base resources path.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="MySqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/booking?useSSL=false"
userId="root"
password="123456">
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<javaModelGenerator targetPackage="com.clycle.booking.entity" targetProject="C:\Users\a243903\projects\booking\webapi\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.clycle.booking.mapper" targetProject="C:\Users\a243903\projects\booking\webapi\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.clycle.booking.mapper" targetProject="C:\Users\a243903\projects\booking\webapi\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="%">
</table>
</context>
</generatorConfiguration>
Create maven Run/Debug Configuration to run this plugin.
It will generate all entity, mapper class and mapper xml automatically. -Dmybatis.generator.overwrite=true, means it will overwrite existing entity or mapper class when run mybatis generator with maven.
Step 3. Add mybatis to this project.
Add mybatis dependency in pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
Create mybatis-config.xml at base resources path.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<typeAliases>
<package name="com.clycle.booking.entity" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value="" />
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/booking" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.clycle.booking.mapper" />
<!--<mapper resource="com/clycle/booking/mapper/ShopMapper.xml" />-->
</mappers>
</configuration>
Add #MapperScan for application main class.
#SpringBootApplication
#MapperScan({"com.clycle.booking.mapper"})
public class BookingApplication {
public static void main(String[] args) {
SpringApplication.run(BookingApplication.class, args);
}
}
Autowired mapper interface to operate your database.
#Autowired
private ShopMapper shopMapper;
#PostMapping(RoutePath.SHOP_LIST)
public List<Shop> GetList() {
try {
return shopMapper.selectAll();
} catch (Exception ex) {
return null;
}
}
You can download this project: https://github.com/yyqian/spring-boot-mybatis-generator .
Everything just work fine on my computer.

Publish JavaScript Client over Apache cxf with Spring configuration

We are publishing a REST-API in our Server-Application. The Rest-API is configured with Spring and uses Apache cxf. The whole configuration is defined in xml and via Annotaions.
Now we have a JavaScript client that uses the rest-api and we want to publish the client (index.html,bundle.js,... ) with the webserver from apache cxf.
Example: localhost:7564/api/v1/webapp
We want to use the embedded web server from Apache cxf to publish the js client. No additinal Tomcat/Apache/... .
There are many exmaples with static-content but none of these are using Spring/ApacheCxf/embeddedWebserver and xml/Annotation-based configuration.
Any ideas?
xml configuration loaded in our Spring applicationcontext.xml:
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<!-- Apache CXF initiale Konfiguration -->
<import resource="classpath:META-INF/cxf/cxf.xml" />
<jaxrs:server
id="jaxrsEmbeddedServer"
address="http://0.0.0.0:7564/api/v1" >
<jaxrs:serviceBeans>
<bean class="com.isp.lea.service.web.api.v1.RootApi" />
...
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean
id="cors-filter"
class="org.apache.cxf.rs.security.cors.CrossOriginResourceSharingFilter" />
...
</jaxrs:providers>
<jaxrs:features>
<ref bean="swagger2Feature" />
...
</jaxrs:features>
</jaxrs:server>
Rest-api example:
#Path( "/" )
#SuppressWarnings( "javadoc" )
public class RootApi extends RestApi
{
#GET
#ApiOperation( value = "Hello World! ",
notes = "Notes...",
tags = { "apm" } )
public String nichts()
{
return "Hello!";
}
}

Spring MVC form validation not working

I am using Spring 4.
My form contains the following variables:
#NotNull
#Email
private String email;
#NotNull
private String firstName;
#NotNull
private String lastName;
#Digits(fraction = 0, integer = 10)
private String phoneNo;
#NotNull
private String role;
My controller:
#Controller
#RequestMapping("/user")
public class UserController {
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView add(#ModelAttribute("user") #Valid UserBean user, BindingResult result) {
String message;
if (result.hasErrors() && user != null)
return new ModelAndView("userAdd");
else {
userService.addUser(user);
message = "Successfully added user";
}
return new ModelAndView("success", "message", message);
}
#RequestMapping(value = "/register")
public ModelAndView register(#ModelAttribute("user") UserBean user, BindingResult result) {
List<String> roles = new ArrayList<String>();
roles.add("Receiver");
roles.add("Resolver");
roles.add("Logger");
Map<String, List<String>> model = new HashMap<String, List<String>>();
model.put("roles", roles);
return new ModelAndView("userAdd", "model", model);
}
}
My jsp:
<c:url var="userAdd" value="user/add.do" />
<sf:form method="post" action="${userAdd}" modelAttribute="user">
<table>
<tr>
<td>First Name</td>
<td><sf:input path="firstName" /><br /> <sf:errors
path="firstName" cssClass="error" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><sf:input path="lastName" /><br /> <sf:errors
path="lastName" cssClass="error" /></td>
</tr>
<tr>
<td>Email</td>
<td><sf:input path="email" /><br /> <sf:errors
path="email" cssClass="error" /></td>
</tr>
<tr>
<td>Phone No.</td>
<td><sf:input path="phoneNo" /><br /> <sf:errors
path="phoneNo" cssClass="error" /></td>
</tr>
<tr>
<td>Role</td>
<td><sf:select path="role" items="${model.roles}" /><br /> <sf:errors
path="role" cssClass="error" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</sf:form>
When I leave the the inputs blank, the form does not validate and does not throw any error. The BindingResult does not have any errors in it.
My libraries are:
My dispatcher-serlvet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- Scans for annotated #Controllers in the classpath -->
<context:component-scan base-package="com.mj.cchp.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="myBeansValidator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<mvc:annotation-driven validator="myBeansValidator" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
My applicationContext is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- Scans for annotated #Controllers in the classpath -->
<context:component-scan base-package="com.mj.cchp">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url" value="jdbc:db2://172.16.2.181:60000/CCHP" />
<property name="username" value="db2inst1" />
<property name="password" value="db2inst1" />
</bean>
</beans>
My web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>CCHP</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
You need to add
<bean id="myBeansValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
and
<mvc:annotation-driven validator="myBeansValidator">
and
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
Should work!
I had a similar problem and in my case it was sufficient to just add dependency for hibernate validator: org.hibernate:hibernate-validator:5.2.4.Final.
The validation is done by LocalValidatorFactoryBean bean and documentation about it comes handy (here).
Yet at the same time it is worth mentioning that you do not have to instantiate LocalValidatorFactoryBean explicitly as long as you use #EnableWebMvc annotation : http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-validation
By default use of #EnableWebMvc or
automatically registers Bean Validation support in Spring MVC through
the LocalValidatorFactoryBean when a Bean Validation provider such as
Hibernate Validator is detected on the classpath.
Hope this helps.
I faced the same problem. I resolved by adding below statement in dispatcher-serlvet.xml file.
<mvc:annotation-driven />
I'm not sure whether you have found ways to fix this. I am facing the same issue as well. and I managed to solve it. The problem with my setting is totally manual and I'm doing big mistake by placing the whole hibernate-validator-5.1.3.Final-dist.zip inside lib folder.
So what I did is I get this 6 files inside "hibernate-validator-5.1.3.Final-dist.zip" in dist folder and place this with web app lib.
classmate-1.0.0.jar
hibernate-validator-5.1.3.Final.jar
javax.el-2.2.4.jar
javax.el-api-2.2.4.jar
jboss-logging-3.1.3.GA.jar
validation-api-1.1.0.Final.jar
This fixed my issue.
i also faced the same issue where my entire code was properly written.
The problem was the different version of jar files that i was using .
I had hibernate-validator-cdi- 5.0.7.Final and hibernate-validator-6.0.2.Final.
Just make sure your jar files are of the same version.
When i kept all the jars of same version, my issue got resolved. I hope this will help you .
You need to add #Valid in register method
#RequestMapping(value = "/register") public ModelAndView register(#Valid #ModelAttribute("user") UserBean user, BindingResult result) {
If you are using hibernate-validator, use version-6.2.4
Version 7 might not work.
In my case hibernate-validator jars are not available in run time. I've copied them to .../WEB-INF/lib/ then it worked correctly.
I added the usual stuff you have done (libraries in pom, #Valid on RequestBody etc)
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b11</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
What the Spring docs (and many blogs) leave it as subtle is that Spring looks for an exit point to throw the error but if that exit doesn't exist, it will reply with 404. After reading a lot especially this blog, adding this class got Spring to recognize #Valid and find an exit point to throw the error
#RestControllerAdvice
#Order(1)
public class RestControllerExceptionHandler {
#RequestMapping(value = { "error/404" }, method = RequestMethod.GET)
#ExceptionHandler(Exception.class)
public String handleUnexpectedException(Exception e) {
return "views/base/rest-error";
}
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ExceptionHandler(MethodArgumentNotValidException.class)
public String handlemethodArgumentNotValid(MethodArgumentNotValidException exception) { //
// TODO you can choose to return your custom object here, which will then get transformed to json/xml etc.
return "Sorry, that was not quite right: " + exception.getMessage();
}
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ExceptionHandler(ConstraintViolationException.class)
public String handleConstraintViolation(ConstraintViolationException exception) { //
// TODO you can choose to return your custom object here, which will then get transformed to json/xml etc.
return "Sorry, that was not quite right: " + exception.getMessage();
}
}
i spent nearly 2 days fixing the same problem and ultimately found one solution, if you still have this problem, i would like to suggest you one answer, in my case, i tried using hibernate-validator-5.1.3.Final-dist.zip,5.2.4.Final-dist.zip, 7.0.0.Final-dist.zip but none of these worked for me but when i used *hibernate-validator-6.2.0.Final-dist*, it supports jarkarta validation but it works perfectly even though people say because of Jakarta Bean Validation it does not work in hibernate-validator's version post 5. it worked miraculously and believe me, it might work for you as well.

Spring and JSF - Dependency Injection fails ServiceBean can not be loaded

i currently hang up in the Spring and JSF Integration. I think i misconfigured something and i can not see what exactly. I get a NULL Pointer Exception because of the Service Tier is not going to be loaded by the JSF Bean. My configuration is the following:
Stacktrace
java.lang.NullPointerException
at com.speterit.auftragssystem.beans.MitarbeiterBean.getMitarbeiterList(MitarbeiterBean.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:484)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
at org.apache.el.parser.AstValue.getValue(AstValue.java:159)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:106)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIData.getValue(UIData.java:553)
at javax.faces.component.UIData.getDataModel(UIData.java:1293)
at javax.faces.component.UIData.setRowIndex(UIData.java:446)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:77)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:824)
at javax.faces.component.UIData.encodeBegin(UIData.java:936)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1661)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1666)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1666)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:389)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:127)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:117)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:135)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:335)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
default.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<h:head>
</h:head>
</head>
<h:body>
#{mitarbeiterBean.getServiceMitarbeiter() ne null ? "true" : "false"}<br />
<h:dataTable value="#{mitarbeiterBean.getMitarbeiterList()}" var="m">
<h:column>
<f:facet name="header">Vorname</f:facet>
#{m.vorname}
</h:column>
<h:column>
<f:facet name="header">Nachname</f:facet>
#{m.nachname}
</h:column>
<h:column>
<f:facet name="header">Geburtsdatum</f:facet>
#{m.geburtsdatum}
</h:column>
</h:dataTable>
</h:body>
The evaluation #{mitarbeiterBean.getServiceMitarbeiter() ne null ? "true" : "false"}<br /> is giving false when I execute the code without the datatable part.
MitarbeiterBean.java
package com.speterit.auftragssystem.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
import com.speterit.auftragssystem.data.service.IServiceMitarbeiter;
#ManagedBean(name = "mitarbeiterBean")
#RequestScoped
public class MitarbeiterBean implements Serializable
{
private static final long serialVersionUID = 1L;
public IServiceMitarbeiter serviceMitarbeiter;
public String vorname;
public String nachname;
public Date geburtsdatum;
public List<Mitarbeiter> getMitarbeiterList()
{
return getServiceMitarbeiter().retrieveAllMitarbeiter();
}
public void addMitarbeiter()
{
Mitarbeiter mitarbeiter = new Mitarbeiter(getVorname(), getNachname(),
getGeburtsdatum());
getServiceMitarbeiter().createMitarbeiter(mitarbeiter);
clearForm();
}
public void clearForm()
{
setVorname("");
setNachname("");
setGeburtsdatum(null);
}
public String getVorname()
{
return vorname;
}
public void setVorname(String vorname)
{
this.vorname = vorname;
}
public String getNachname()
{
return nachname;
}
public void setNachname(String nachname)
{
this.nachname = nachname;
}
public Date getGeburtsdatum()
{
return geburtsdatum;
}
public void setGeburtsdatum(Date geburtsdatum)
{
this.geburtsdatum = geburtsdatum;
}
public IServiceMitarbeiter getServiceMitarbeiter()
{
return serviceMitarbeiter;
}
public void setServiceMitarbeiter(IServiceMitarbeiter serviceMitarbeiter)
{
this.serviceMitarbeiter = serviceMitarbeiter;
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Hibernate -->
<beans:bean id="hibernateSessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<beans:property name="configLocation" value="classpath:hibernate.cfg.xml" />
<beans:property name="configurationClass"
value="org.hibernate.cfg.AnnotationConfiguration" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect
</beans:prop>
<beans:prop key="hibernate.c3p0.min_size">5</beans:prop>
<beans:prop key="hibernate.c3p0.max_size">20</beans:prop>
<beans:prop key="hibernate.c3p0.timeout">1800</beans:prop>
<beans:prop key="hibernate.c3p0.max_statements">50</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernateSessionFactory" />
</beans:bean>
<!-- Model Declaration -->
<beans:bean id="Mitarbeiter" class="com.speterit.auftragssystem.data.model.Mitarbeiter"/>
<!-- DAO Declaration -->
<beans:bean id="DaoMitarbeiter" class="com.speterit.auftragssystem.data.dao.DaoMitarbeiter">
<beans:property name="sessionFactory" ref="SessionFactory" />
</beans:bean>
<!-- Service Declaration -->
<beans:bean id="ServiceMitarbeiter" class="com.speterit.auftragssystem.data.service.ServiceMitarbeiter">
<beans:property name="daoMitarbeiter" ref="DaoMitarbeiter" />
</beans:bean>
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
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-facesconfig_2_0.xsd"
version="2.0">
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
<managed-bean>
<managed-bean-name>mitarbeiterBean</managed-bean-name>
<managed-bean-class>com.speterit.auftragssystem.beans.MitarbeiterBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>serviceMitarbeiter</property-name>
<value>#{ServiceMitarbeiter}</value>
</managed-property>
</managed-bean>
</faces-config>
IServiceMitarbeiter.java
package com.speterit.auftragssystem.data.service;
import java.util.List;
import com.speterit.auftragssystem.data.dao.IDaoMitarbeiter;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
public interface IServiceMitarbeiter
{
public List<Mitarbeiter> retrieveAllMitarbeiter();
public Mitarbeiter retrieveMitarbeiter(long personalnummer);
public Mitarbeiter createMitarbeiter(Mitarbeiter mitarbeiter);
public Mitarbeiter updateMitarbeiter(Mitarbeiter mitarbeiter);
public IDaoMitarbeiter getDaoMitarbeiter();
public void setDaoMitarbeiter(IDaoMitarbeiter daoMitarbeiter);
}
ServiceMitarbeiter.java
package com.speterit.auftragssystem.data.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.speterit.auftragssystem.data.dao.IDaoMitarbeiter;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
#Transactional(readOnly = true)
public class ServiceMitarbeiter implements IServiceMitarbeiter
{
IDaoMitarbeiter daoMitarbeiter;
#Transactional(readOnly = true)
public List<Mitarbeiter> retrieveAllMitarbeiter()
{
return daoMitarbeiter.getAll();
}
#Transactional(readOnly = true)
public Mitarbeiter retrieveMitarbeiter(long personalnummer)
{
return daoMitarbeiter.getByPersonalnummer(personalnummer);
}
#Transactional(readOnly = false)
public Mitarbeiter createMitarbeiter(Mitarbeiter mitarbeiter)
{
return daoMitarbeiter.create(mitarbeiter);
}
#Transactional(readOnly = false)
public Mitarbeiter updateMitarbeiter(Mitarbeiter mitarbeiter)
{
return daoMitarbeiter.persistOrMerge(mitarbeiter);
}
public IDaoMitarbeiter getDaoMitarbeiter()
{
return daoMitarbeiter;
}
public void setDaoMitarbeiter(IDaoMitarbeiter daoMitarbeiter)
{
this.daoMitarbeiter = daoMitarbeiter;
}
}
I'm happy for every fast clue :) Because i got no idea anymore
With org.springframework.web.jsf.el.SpringBeanFacesELResolver your class needs to be a
simple Spring component. Remove #ManagedBean and add #Component annotations.
You've created another instance of MitarbeiterBean managed by JSF via #ManagedBean annotation and it is not the same bean that is managed by Spring so the serviceMitarbeiter field is not injected. Just forget about JSF managed beans and use Spring components in JSF.
Also replace javax.faces.bean sope annotations with Spring #Scope.
e.g. #RequestScoped -> #Scope("request")

How to start myBatis implemention with spring?

I want to work with myBatis. I have read MyBatis-3-user-guide. Now i am trying to implement it. Recently i have learned spring. So it is difficult for me to implement it. So i need some helpful resource by which i can implement it step by step.
Add the MyBatis-Spring jar in your class path at first
Start with your spring context file.In your context file add following lines
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="yourDriverClassName"
p:url="yourUrl"
p:username="yourUsername"
p:password="yourPassword" />
<beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="configLocation" value="/WEB-INF/mybatis-config.xml" />
</beans:bean>
<beans:bean id="userDao" class="com.yourcomp.dao.Userdao">
<beans:property name="sqlSessionFactory" ref="sqlSessionFactory" />
</beans:bean>
your mybatis-config.xml should be something like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
</settings>
<typeAliases>
<typeAlias alias="User" type ="com.yourcomp.domain.User" />
</typeAliases>
<mappers>
<mapper resource="com/yourcomp/domain/UserMapper.xml"/>
<mapper resource="com/yourcomp/domain/AnotherDomainObjectMapper.xml"/>
</mappers>
</configuration>
and your userMapper.xml in src/com/yourcomp/domain/ might be something like this
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--<mapper namespace="org.pbl.rms.RMSUserDao">-->
<mapper namespace="com.yourcomp.domain.User">
<resultMap id="userMap" type="User">
<id property="userId" column="USER_ID" javaType="int" jdbcType="NUMERIC"/>
<result property="userName" column="USER_NAME" javaType="String" jdbcType="VARCHAR"/>
<result property="userFullName" column="USER_FULL_NAME" javaType="String" jdbcType="VARCHAR"/>
<result property="password" column="PASSWORD" javaType="String" jdbcType="VARCHAR"/>
<result property="passwordExpiryDate" column="PASWRD_EXPIRY_DATE" javaType="java.util.Date" jdbcType="DATE"/>
<result property="status" column="STATUS" javaType="_integer" jdbcType="DECIMAL"/>
</resultMap>
<select id="getUserById" parameterType="map" resultMap="userMap">
select * from user where USER_ID=#{userId}
</select>
</mapper>
now in your DAO layer you might have class like follows:
public class UserDAO{
private SqlSessionFactory sqlSessionFactory;
public UserDAO() {
}
public UserDAO(SqlSessionFactory sqlSessionFactory ) {
this.sqlSessionFactory = sqlSessionFactory;
}
public String getUserById(Integer userId) {
SqlSession session = sqlSessionFactory.openSession();
String name=null;
try {
name = (String)session.selectOne("com.yourcomp.domain.User.getUserById",userId);
}catch(Exception e){
}finally {
session.close();
}
return name;
}
}
You need MyBatis-Spring for this . See the reference here and here These provide you the step by step configs . If you need any specific details , you need to re frame your query .
Also check the spring reference for IBatis support.

Resources