nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field - spring

I'm trying to wire JERSEY rest services with Spring and i'm facing this exception.
PodcastResource
package com.integration.messenger.resources;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.integration.messenger.model.Podcast;
import com.integration.messenger.service.PodcastService;
#Path("/podcasts")
#Component
public class PodcastResource {
#Autowired
PodcastService podcastService;
#GET
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Podcast> getPodcasts(){
return podcastService.getAllPodcasts();
}
/*#GET
#Produces({ MediaType.APPLICATION_JSON})
public String getMessage(){
return "Helooo";
}*/
}
PodcastService
package com.integration.messenger.service;
import java.util.List;
import com.integration.messenger.model.Podcast;
public interface PodcastService {
List<Podcast> getAllPodcasts();
}
PodcastServiceImp
package com.integration.messenger.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.integration.messenger.model.Podcast;
import com.integration.messenger.repository.PodcastRepository;
#Service("podcastService")
public class PodcastServiceImp implements PodcastService {
#Autowired
PodcastRepository podcastRepository;
private Map<Long, Podcast> podcasts = podcastRepository.getPodcasts();
public PodcastServiceImp() {
podcasts.put(1L, new Podcast(1, "Hello World News", "How to Programme", "www.podcastpedia.com/How to Programme", "Programme"));
podcasts.put(2L, new Podcast(2, "Hello Jersey News", "Restfull Implementation", "www.podcastpedia.com/Restfull Implementation", "Restfull"));
}
public List<Podcast> getAllPodcasts() {
return new ArrayList<Podcast>(podcasts.values());
}
}
PodcastRepository
package com.integration.messenger.repository;
import java.util.Map;
import com.integration.messenger.model.Podcast;
public interface PodcastRepository {
Map<Long, Podcast> getPodcasts();
}
PodcastRepositoryImpl
package com.integration.messenger.repository;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.integration.messenger.model.Podcast;
#Repository
public class PodcastRepositoryImpl implements PodcastRepository {
private static Map<Long, Podcast> podcasts = new HashMap<Long, Podcast>();
public Map<Long, Podcast> getPodcasts() {
return podcasts;
}
}
Podcast
package com.integration.messenger.model;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Podcast implements Serializable{
private static final long serialVersionUID = -1471231465385956738L;
#XmlElement(name = "id")
private long id;
#XmlElement(name = "feed")
private String feed;
#XmlElement(name = "title")
private String title;
#XmlElement(name = "linkOnPodcastpedia")
private String linkOnPodcastpedia;
#XmlElement(name = "description")
private String description;
public Podcast(int id, String feed, String title, String linkOnPodcastpedia, String description) {
this.id = id;
this.feed = feed;
this.title = title;
this.linkOnPodcastpedia = linkOnPodcastpedia;
this.description = description;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFeed() {
return feed;
}
public void setFeed(String feed) {
this.feed = feed;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLinkOnPodcastpedia() {
return linkOnPodcastpedia;
}
public void setLinkOnPodcastpedia(String linkOnPodcastpedia) {
this.linkOnPodcastpedia = linkOnPodcastpedia;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
MyApplication
package com.integration.messenger;
import org.glassfish.jersey.jackson1.Jackson1Feature;
import org.glassfish.jersey.server.ResourceConfig;
import com.integration.messenger.resources.PodcastResource;
public class MyApplication extends ResourceConfig{
/**
* Register JAX-RS application components.
*/
public MyApplication() {
// register application resources
register(PodcastResource.class);
// register features
// register Jackson JSON providers - for the application to understand JSON data
register(Jackson1Feature.class);
}
}
ApplicationContext.xml
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:component-scan base-package="com.integration.messenger" />
</beans>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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">
<servlet>
<servlet-name>jersey-Spring-Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.integration.messenger.MyApplication</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-Spring-Application</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<display-name>Restful Web Application</display-name>
</web-app>
ERROR:
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'podcastResource': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.integration.messenger.service.PodcastService com.integration.messenger.resources.PodcastResource.podcastService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'podcastService' defined in file [C:\My_Workspaces\My_Work\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\messenger\WEB-INF\classes\com\integration\messenger\service\PodcastServiceImp.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.integration.messenger.service.PodcastServiceImp]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

I guess you need to make some configuration related changes to integrate Spring with Jersey. Some I can think of,
Register Spring ContextLoaderListener. (This loads the spring xml file).
Make use of spring related jersey servlet com.sun.jersey.spi.spring.container.servlet.SpringServlet or org.glassfish.jersey.servlet.ServletContainer(in the latest versions I believe)
Specify in the spring xml file.
-Madhu.

Related

How to solve error message when try to start jpa on spring-boot?

I have spring+jpa+rest application on spring-boot(try to implement)
Application for spring-boot:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.persistence.PersistenceContext;
#SpringBootApplication
#ComponentScan("package")
#EnableJpaRepositories(basePackages = "package.dao", entityManagerFactoryRef = "emf")
#ImportResource("applicationContext.xml")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I have rest - controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import package.myService;
#RestController
public class TestController {
#Autowired
private MyService myService;
#PostMapping("create")
public void test1(){
}
#PostMapping("{id}")
public void test2(#RequestBody Object object){
}
#GetMapping("{id}")
public void test3(#PathVariable Long id){
}
}
Entity:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.math.BigDecimal;
#Entity
public class MyEntity {
#Id
#GeneratedValue
private Long id;
private String name;
public MyEntity() {
}
public MyEntity(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Repository is:
MyEntityRepository:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
#Repository
public interface MyEntityRepositoryextends JpaRepository<myEntity, Long>{
public void findNameById(#Param("id") Long id);
}
application context in resouces:
<?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:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
<bean id="riskMetricService" class="ru.sbrf.risks.services.data.service.RiskMetricServiceImpl"/>
</beans>
If needs, I can add pom.xml
I have error message when try to strat: APPLICATION FAILED TO START
Description:
Parameter 0 of constructor in
org.springframework.data.rest.webmvc.RepositorySearchController
required a bean named 'emf' that could not be found.
Action:
Where need to locate file with dbconnection configs?
How to solve this error message?
in your application you are referencing an entity manager bean called emf
entityManagerFactoryRef = "emf"
You should define it. you can do it in your application context or in a
#Configuration Class.
For example you could define it this way :
<bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
......
</bean>

#Autowired not working when using spring-security (neo4j as database)

I forked an example-spring-data-neo4j project, and build my own 'StigMod' project from it.
Everything works fine, until I tried to change the controller-service-repository structure of this project.
My Controller -> Service -> Repository structure.
#Controller
public class StigModController {
...
#Autowired
StigmodUserDetailsService stigmodUserDetailsService;
...
}
#Service
public class StigmodUserDetailsService implements UserDetailsService {
...
#Autowired
private UserRepository userRepository;
...
}
public interface UserRepository extends GraphRepository<User> {
User findByMail(String mail);
}
Structure in the example:
#Controller
public class AuthController {
...
#Autowired
UserRepository userRepository;
...
}
public interface UserRepository extends GraphRepository<User>, CineastsUserDetailsService {
User findByLogin(String login);
}
#Service
public class CineastsUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
}
public class UserRepositoryImpl implements CineastsUserDetailsService {
#Autowired
private UserRepository userRepository;
}
After my refactoring, a problem popped out:
The StigmodUserDetailsService class is annotated with #Service. Component scan is enabled in package net.stigmod, and my IDE actually could recognize all the #Autowire dependencies in all files.
However, the autowired field stigmodUserDetailsService in StigModController.java could not be initialized during deployment.
I tried several methods proposed by people in some similar questions, but they did not work. I guess there is soming wrong with the spring-security dymamic object feature, but I am not sure.
I posted most of the related complete codes below. Hope someone could help me out. Thank you so much!
### ERROR in Tomcat Localhost Log during deployment ###
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stigModController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: net.stigmod.service.StigmodUserDetailsService net.stigmod.controller.StigModController.stigmodUserDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [net.stigmod.service.StigmodUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: net.stigmod.service.StigmodUserDetailsService net.stigmod.controller.StigModController.stigmodUserDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [net.stigmod.service.StigmodUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 56 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [net.stigmod.service.StigmodUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 58 more
### web.xml ###
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<display-name>Spring MVC Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-security.xml
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>StigMod</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StigMod</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
### applicationContext.xml ###
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config/>
<context:spring-configured/>
<context:component-scan base-package="net.stigmod">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<tx:annotation-driven mode="proxy"/>
</beans>
### applicationContext-security.xml ###
<?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:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<context:component-scan base-package="net.stigmod">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<security:global-method-security secured-annotations="enabled">
</security:global-method-security>
<security:http> <!-- use-expressions="true" -->
<security:intercept-url pattern="/" access="isAnonymous()"/>
<security:intercept-url pattern="/static/**" access="permitAll"/>
<security:intercept-url pattern="/about" access="permitAll"/>
<security:intercept-url pattern="/signin*" access="isAnonymous()"/>
<security:intercept-url pattern="/signup*" access="isAnonymous()"/>
<security:intercept-url pattern="/**" access="isFullyAuthenticated()"/>
<security:form-login login-page="/signin"
authentication-failure-url="/signin?login_error=true"
default-target-url="/user"
login-processing-url="/signin"
username-parameter="mail"
password-parameter="password"/>
<security:access-denied-handler error-page="/denied" />
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="stigmodUserDetailsService">
<security:password-encoder hash="md5">
<security:salt-source system-wide="xxxxxx"/>
</security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
</beans>
### StigMod-servelet.xml ###
<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/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">
<context:component-scan base-package="net.stigmod.controller"/>
<mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
<mvc:annotation-driven/>
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="configLocation" value="/WEB-INF/velocity.properties"/>
<property name="resourceLoaderPath" value="/WEB-INF/velocity/"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".vm"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
</bean>
</beans>
### Application.java ###
package net.stigmod;
import net.stigmod.util.config.Config;
import net.stigmod.util.config.ConfigLoader;
import net.stigmod.util.config.Neo4j;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.server.Neo4jServer;
import org.springframework.data.neo4j.server.RemoteServer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableNeo4jRepositories("net.stigmod.repository")
#EnableTransactionManagement
#ComponentScan("net.stigmod")
public class Application extends Neo4jConfiguration {
// Common settings
private Config config = ConfigLoader.load();
private Neo4j neo4j = config.getNeo4j();
private String host = neo4j.getHost();
private String port = neo4j.getPort();
private String username = neo4j.getUsername();
private String password = neo4j.getPassword();
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("net.stigmod.domain");
}
#Override
#Bean
public Neo4jServer neo4jServer() {
return new RemoteServer("http://" + host + ":" + port, username, password);
}
#Override
#Bean
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
return super.getSession();
}
}
### StigModController.java ###
package net.stigmod.controller;
import net.stigmod.domain.node.User;
import net.stigmod.service.StigmodUserDetailsService;
import net.stigmod.util.config.Config;
import net.stigmod.util.config.ConfigLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#Controller
public class StigModController {
// Common settings
private Config config = ConfigLoader.load();
private String host = config.getHost();
private String port = config.getPort();
#Autowired
StigmodUserDetailsService stigmodUserDetailsService;
private final static Logger logger = LoggerFactory.getLogger(UserController.class);
// front page
#RequestMapping(value="/", method = RequestMethod.GET)
public String index(ModelMap model) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "index");
return "index";
}
// about this web app
#RequestMapping(value="/about", method = RequestMethod.GET)
public String about(ModelMap model) {
final User user = stigmodUserDetailsService.getUserFromSession();
model.addAttribute("user", user);
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "about");
return "about";
}
// sign up page GET
#RequestMapping(value="/signup", method = RequestMethod.GET)
public String reg(ModelMap model, HttpServletRequest request) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Sign Up");
// CSRF token
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrfToken != null) {
model.addAttribute("_csrf", csrfToken);
}
return "signup";
}
// sign up page POST
#RequestMapping(value="/signup", method = RequestMethod.POST)
public String regPost(
#RequestParam(value = "mail") String mail,
#RequestParam(value = "password") String password,
#RequestParam(value = "password-repeat") String passwordRepeat,
ModelMap model, HttpServletRequest request) {
try {
stigmodUserDetailsService.register(mail, password, passwordRepeat);
return "redirect:/user";
} catch(Exception e) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Sign Up");
// CSRF token
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrfToken != null) {
model.addAttribute("_csrf", csrfToken);
}
model.addAttribute("mail", mail);
model.addAttribute("error", e.getMessage());
return "signup";
}
}
// sign in page GET (POST route is taken care of by Spring-Security)
#RequestMapping(value="/signin", method = RequestMethod.GET)
public String login(ModelMap model, HttpServletRequest request) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Sign In");
// CSRF token
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrfToken != null) {
model.addAttribute("_csrf", csrfToken);
}
return "signin";
}
// sign out
#RequestMapping(value="/signout", method = RequestMethod.GET)
public String logout (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/signin";
}
// Denied page GET
#RequestMapping(value="/denied", method = RequestMethod.GET)
public String reg(ModelMap model) {
model.addAttribute("host", host);
model.addAttribute("port", port);
model.addAttribute("title", "Denied");
return "denied";
}
}
### UserRepository.java ###
package net.stigmod.repository.node;
import net.stigmod.domain.node.User;
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends GraphRepository<User> {
User findByMail(String mail);
}
### StigmodUserDetails.java ###
package net.stigmod.service;
import net.stigmod.domain.node.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
public class StigmodUserDetails implements UserDetails {
private final User user;
public StigmodUserDetails(User user) {
this.user = user;
}
#Override
public Collection<GrantedAuthority> getAuthorities() {
User.SecurityRole[] roles = user.getRole();
if (roles == null) {
return Collections.emptyList();
}
return Arrays.<GrantedAuthority>asList(roles);
}
#Override
public String getPassword() {
return user.getPassword();
}
#Override
public String getUsername() {
return user.getMail();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
public User getUser() {
return user;
}
}
### StigmodUserDetailsService.java ###
package net.stigmod.service;
import net.stigmod.domain.node.User;
import net.stigmod.repository.node.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class StigmodUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
public StigmodUserDetailsService() {}
public StigmodUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public StigmodUserDetails loadUserByUsername(String mail) throws UsernameNotFoundException {
final User user = userRepository.findByMail(mail);
if (user == null) {
throw new UsernameNotFoundException("Username not found: " + mail);
}
return new StigmodUserDetails(user);
}
public User getUserFromSession() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
Object principal = authentication.getPrincipal();
if (principal instanceof StigmodUserDetails) {
StigmodUserDetails userDetails = (StigmodUserDetails) principal;
return userDetails.getUser();
}
return null;
}
#Transactional
public User register(String mail, String password, String passwordRepeat) {
User found = userRepository.findByMail(mail);
if (found != null) {
throw new RuntimeException("Email already taken: " + mail);
}
if (password == null || password.isEmpty()) {
throw new RuntimeException("No password provided.");
}
if (passwordRepeat == null || passwordRepeat.isEmpty()) {
throw new RuntimeException("No password-repeat provided.");
}
if (!password.equals(passwordRepeat)) {
throw new RuntimeException("Passwords provided do not equal.");
}
User user = userRepository.save(new User(mail, password, User.SecurityRole.ROLE_USER));
setUserInSession(user);
return user;
}
void setUserInSession(User user) {
SecurityContext context = SecurityContextHolder.getContext();
StigmodUserDetails userDetails = new StigmodUserDetails(user);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(), userDetails.getAuthorities());
context.setAuthentication(authentication);
}
}

context.lookup in not working in weblogic

i am new in ejb3 application
my project is:
ServletController.java
package controller;
import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.HelloUser;
public class ServletController extends HttpServlet {
#Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
try {
InitialContext Context = new InitialContext();
Context context = new InitialContext();
HelloUser helloUser = (HelloUser) context.lookup("ejb3/" + HelloUser.class.getSimpleName() + "/local");
System.out.println(".................................");
helloUser.sayHello("reza");
arg1.sendRedirect("reza");
} catch (Exception e) {
e.printStackTrace();
}
}
}
HelloUser.java:
package com;
import javax.ejb.Local;
#Local
public interface HelloUser {
public void sayHello(String name);
}
HelloUserBean.java
package com;
import javax.ejb.Stateless;
#Stateless
public class HelloUserBean implements HelloUser {
public HelloUserBean() {
}
public void sayHello(String name) {
System.out.println("Hello " + name + " welcome to EJB 3!");
}
}
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Baharan-Framework</display-name>
<welcome-file-list>
<welcome-file>Index.jsp</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>controller.ServletController</servlet-class>
</servlet>
</web-app>
the following error is raised when ServletController is called by webbrowser(URL is:http://localhost:7001/weblogic/rest/jkfg):
javax.naming.NameNotFoundException: While trying to lookup 'ejb3.HelloUser/local' didn't find subcontext 'ejb3'. Resolved ''; remaining name 'ejb3/HelloUser/local'
at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
First of all, Weblogic print all jndi names assigned to every Enterprise bean, and you can get it directly. The second, remove context.lookup("ejb3/" + HelloUser.class.getSimpleName() + "/local"); then in simple cases this function can helps you:
public static <T>T lookupBean(Class<T> beanClass) {
final String jndiName = "java:module/" + beanClass.getSimpleName();
logger.info("lookup : {}", jndiName);
try {
T bean = InitialContext.doLookup(jndiName);
logger.info("detected : {}", bean);
return bean;
}
catch(NamingException e) {
logger.error(e.getMessage(), e);
return null;
}
Can you provide me deployments log?? and rather then trying using initialcontext lookup with #EJB annotation.

Problems with CDI - ( Weld + TomCat7 + JSF )

I'm starting a project with CDI using weld, and am getting the following error when I try to injection:
#Inject
private UserRepository repository;
Console:
INFO: Starting Servlet Engine: Apache Tomcat/7.0.12
13:16:22,859 INFO servletWeldServlet:57 - WELD-ENV-001008: Initialize Weld using ServletContainerInitializer
13:16:22,875 INFO Version:151 - WELD-000900: 2.2.5 (Final)
13:16:22,906 INFO Bootstrap:206 - WELD-000101: Transactional services not available. Injection of #Inject UserTransaction not available. Transactional observers will be invoked synchronously.
13:16:22,937 WARN Interceptor:47 - WELD-001700: Interceptor annotation class javax.ejb.PostActivate not found, interception based on it is not enabled
13:16:22,937 WARN Interceptor:47 - WELD-001700: Interceptor annotation class javax.ejb.PrePassivate not found, interception based on it is not enabled
13:16:23,046 INFO servletTomcat:45 - WELD-ENV-001100: Tomcat 7+ detected, CDI injection will be available in Servlets, Filters and Listeners.
org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type UserRepository with qualifiers #Default
at injection point [BackedAnnotatedField] #Inject private br.com.controllers.UserController.repository
at br.com.controllers.UserController.repository(UserController.java:0)
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:372)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:293)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:167)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:531)
at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:68)
at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:66)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
EntityManagerFactory.java
package br.com.util;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class EntityManagerFactory {
#PersistenceContext(unitName="default")
private EntityManager em;
#Produces
public EntityManager create() {
return em;
}
public void close(#Disposes EntityManager em) {
em.close();
}
}
Repository.java
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public abstract class Repository<T, I extends Serializable> {
#Inject
protected final EntityManager entityManager;
protected final Class<T> clazz;
protected Repository(EntityManager entityManager) {
this.entityManager = entityManager;
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.clazz = clazz;
}
public void refresh(T entity){
entityManager.refresh(entity);
}
public void create(T entity) {
entityManager.persist(entity);
}
public T update(T entity) {
return entityManager.merge(entity);
}
public void destroy(T entity) {
entityManager.remove(entity);
}
public T find(I id) {
return entityManager.find(clazz, id);
}
public List<T> findAll() {
TypedQuery<T> query = entityManager.createQuery("FROM " + clazz.getName() ,clazz);
List<T> resultList = query.getResultList();
return resultList;
}
}
UserRepositoryImpl.java
package br.com.repositories;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import br.com.models.User;
#Transactional
public class UserRepositoryImpl extends Repository<User, Long >implements UserRepository {
protected UserRepositoryImpl(EntityManager entityManager) {
super(entityManager);
}
}
UserController.java
package br.com.controllers;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import br.com.repositories.UserRepository;
#Named("userController")
#RequestScoped
public class UserController {
#Inject
private UserRepository repository;
UserController(){
}
#PostConstruct
public void init(){
System.out.println("started");
}
public String getMessage(){
return "test";
}
public void create(){
System.out.println("test method");
}
}
META-INF/beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>
META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Manager pathname=""/> <!-- disables storage of sessions across restarts -->
<Resource name="BeanManager"
auth="Container"
type="javax.enterprise.inject.spi.BeanManager"
factory="org.jboss.weld.resources.ManagerObjectFactory"/>
</Context>
WEB-INF/web.xml
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>wochenbericht</display-name>
<welcome-file-list>
<welcome-file>index.jsf</welcome-file>
</welcome-file-list>
<!-- CDI - WELD -->
<listener>
<listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
</listener>
<resource-env-ref>
<resource-env-ref-name>BeanManager</resource-env-ref-name>
<resource-env-ref-type>
javax.enterprise.inject.spi.BeanManager
</resource-env-ref-type>
</resource-env-ref>
<!-- JSF -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<!-- SESSION TIMEOUT -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- CONTEXT LOCAL -->
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
<param-value>2</param-value>
</context-param>
<context-param>
<param-name>javax.faces.WEBAPP_RESOURCES_DIRECTORY</param-name>
<param-value>/assets</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- SECURITY SETTINGS -->
<security-constraint>
<display-name>Restrict direct access to XHTML files</display-name>
<web-resource-collection>
<web-resource-name>XHTML files</web-resource-name>
<url-pattern>*.xhtml</url-pattern>
</web-resource-collection>
<auth-constraint />
</security-constraint>
My Libs:
antlr-2.7.7.jar
aopalliance.jar
c3p0-0.9.1.jar
cdi-api-1.1.jar
dom4j-1.6.1.jar
EasyCriteria-3.1.0.jar
hibernate-c3p0-4.3.6.Final.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.6.Final.jar
hibernate-entitymanager-4.3.5.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-validator-4.3.0.Final.jar
javassist-3.18.1-GA.jar
javax.inject.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jsf-api-2.2.8.jar
jsf-impl-2.2.8.jar
log4j-1.2.16.jar
postgresql-9.2-1003.jdbc4.jar
slf4j-api-1.6.6.jar
slf4j-jdk14-1.6.6.jar
slf4j-log4j12-1.6.1.jar
validation-api-1.0.0.GA.jar
weld-se-core-2.2.5.Final.jar
weld-servlet-2.2.5.Final.jar
weld-servlet-core-2.2.5.Final.jar
Can anyone help me? thank you!
Your first problem is that UserRepositoryImpl class doesn't have default (empty) constructor, and nither there is #Produces method, so there is no way to instantiate it. Remove EntityManager entityManager from constructors from Repository and UserRepositoryImpl classes.
Change the constructor in Repository to:
protected Repository() {
/// this.entityManager = entityManager; // <= this is already injected by
// #Inject protected final EntityManager entityManager;
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.clazz = clazz;
}
Your second problem will be incorrect injection of PersistenceContext. You either need to use EJB (to inject EntityManager via #PersistenceContext) or for web modules use:
#PersistenceUnit(unitName="default")
EntityManagerFactory emf;
...
EntityManager em = emf.createEntityManager();
And your third problem will be transactions - again you either need to switch to EJB, or handle transactions while persisting your beans.
I'd recommend first read the following before coding:
CDI documentation
Contexts and Dependency Injection for Java EE (Tutorial)
JPA (Tutorial)
Managing Entities
#Gas Thanks for you feedback and links, now works, I do not know if it's the best way:
UserRepositoryImpl
package br.com.repositories;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import br.com.models.User;
#Transactional
public class UserRepositoryImpl extends Repository<User, Long >implements UserRepository {
#Inject
protected UserRepositoryImpl(EntityManager entityManager) {
super(entityManager);
}
}
Repository
package br.com.repositories;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public abstract class Repository<T, I extends Serializable> {
protected final EntityManager entityManager;
protected final Class<T> clazz;
protected Repository(EntityManager entityManager) {
this.entityManager = entityManager;
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.clazz = clazz;
}
public void refresh(T entity){
entityManager.refresh(entity);
}
public void create(T entity) {
entityManager.persist(entity);
}
public T update(T entity) {
return entityManager.merge(entity);
}
public void destroy(T entity) {
entityManager.remove(entity);
}
public T find(I id) {
return entityManager.find(clazz, id);
}
public List<T> findAll() {
TypedQuery<T> query = entityManager.createQuery("FROM " + clazz.getName() ,clazz);
return query.getResultList();
}
}
EntityManagerProducer
package br.com.util;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
#ApplicationScoped
public class EntityManagerProducer {
private EntityManagerFactory factory;
public EntityManagerProducer() {
factory = Persistence.createEntityManagerFactory("default");
}
#Produces #RequestScoped
public EntityManager createEntityManager() {
return factory.createEntityManager();
}
public void closeEntityManager(#Disposes EntityManager manager) {
manager.close();
}
}
UserController
package br.com.vw.controllers;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import br.com.models.User;
import br.com.repositories.UserRepository;
#Named("userController")
#RequestScoped
public class UserController {
#Inject UserRepository userRepository;
UserController(){
}
#PostConstruct
public void init(){
System.out.println("Inicialilizado o construtor");
}
public String getMessage(){
return "Conteúdo da mensagem";
}
public void create(){
System.out.println("Método create disparado");
User user = new User();
user.setEmail("email#uol.com.br");
user.setName("Marcos de Freitas");
userRepository.create(user);
}
}
Tks

NoSuchBeanDefinitionException Spring 3.2.2 Hibernate 4 using annotation configuration building with Maven 3

What am I missing?
I am trying to create a basic SpringMVC application using Hibernate. I have another SpringMVC application that I model it after and it works.
I have apparently missed something and I am at a loss. Any help here would be much appreciated. Just another pair of eyes might solve the problem. Maybe I am blind.
Basically the error is telling me that I cannot create customerService bean in my controller because the customerDao bean cannot be located and therefore cannot be injected into the service.
When I use Intellij I am able to follow the bean references and everything appears
to be wired up correctly but when I run in tomcat6 or tomcat7 get the following errors:
Sep 26, 2013 10:13:02 AM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mydomain.dao.CustomerDao com.mydomain.service.CustomerService.customerDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mydomain.dao.CustomerDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1122)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mydomain.dao.CustomerDao com.mydomain.service.CustomerService.customerDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mydomain.dao.CustomerDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 21 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mydomain.dao.CustomerDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 23 more
Sep 26, 2013 10:13:02 AM org.apache.catalina.core.StandardContext startInternal
Code as follows:
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.mydomain.config.WebConfig</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.mydomain.config.WebConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
WebConfig.java
package com.mydomain.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#Configuration
#Import({DaoConfig.class, ServiceConfig.class, ControllerConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public Validator getValidator(){
return new LocalValidatorFactoryBean();
}
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
DaoConfig.java
package com.mydomain.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan({"com.mydomain.dao", "com.mydomain.service"})
public class DaoConfig {
#Bean
public LocalSessionFactoryBean getSessionFactory(){
final LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(getDataSource());
sessionFactoryBean.setPackagesToScan(new String[]{"com.mydomain.domain"});
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
#Bean
public DataSource getDataSource(){
final DriverManagerDataSource dmds = new DriverManagerDataSource();
dmds.setDriverClassName("com.mysql.jdbc.Driver");
dmds.setUsername("root");
dmds.setPassword("");
dmds.setUrl("jdbc:mysql://localhost/commandsearch");
return dmds;
}
#Bean
public HibernateTransactionManager transactionManager() {
final HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(getSessionFactory().getObject());
return txManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", "update");
setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
setProperty("hibernate.show_sql", "true");
}
};
}
}
IAbstractDao.java
package com.mydomain.dao;
import java.io.Serializable;
import java.util.List;
public interface IAbstractDao <T extends Serializable> {
T findOne(final long id);
List<T> findAll();
void save(final T t);
void delete(final T t);
void deleteById(final long id);
}
AbstractHibernateDao.java
package com.mydomain.dao;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class AbstractHibernateDao<T extends Serializable> implements IAbstractDao<T> {
protected Class<T> entityClass;
protected final Log logger = LogFactory.getLog(getClass());
protected AbstractHibernateDao(Class<T> entityClass){
this.entityClass = entityClass;
}
#Autowired
private SessionFactory sessionFactory;
protected final Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
#Override
public T findOne(final long id) {
return ((T) getCurrentSession().get(entityClass, id));
}
#Override
public List<T> findAll() {
return (List<T>)getCurrentSession().createQuery("from " + entityClass.getName()).list();
}
#Override
public void save(final T t) {
getCurrentSession().saveOrUpdate(t);
}
#Override
public void delete(final T t) {
getCurrentSession().delete(t);
}
#Override
public void deleteById(final long id) {
final T entity = findOne(id);
delete(entity);
}
}
CustomerDao.java
package com.mydomain.dao;
import org.springframework.stereotype.Repository;
import com.mydomain.domain.Customer;
#Repository
public class CustomerDao extends AbstractHibernateDao<Customer> {
public CustomerDao(){
this(Customer.class);
}
public CustomerDao(Class<Customer> entityClass){
super(entityClass);
}
}
ServiceConfig.java
package com.mydomain.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan({"com.mydomain.service"})
public class ServiceConfig {
}
AbstractService.java
package com.mydomain.service;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;
import com.mydomain.dao.IAbstractDao;
#Transactional
public abstract class AbstractService<T extends Serializable> {
protected final Log logger = LogFactory.getLog(getClass());
public T findOne(final long id) {
return getDao().findOne(id);
}
public List<T> findAll() {
return getDao().findAll();
}
public void save(final T entity) {
getDao().save(entity);
}
public void delete(final T entity) {
getDao().delete(entity);
}
public void deleteById(final long entityId) {
getDao().deleteById(entityId);
}
protected abstract IAbstractDao<T> getDao();
}
CustomerService.java
package com.mydomain.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mydomain.dao.CustomerDao;
import com.mydomain.dao.IAbstractDao;
import com.mydomain.domain.Customer;
#Service
#Transactional
public class CustomerService extends AbstractService<Customer>{
#Autowired
private CustomerDao customerDao;
#Override
protected IAbstractDao<Customer> getDao() {
return customerDao;
}
}
Your immediate problem is this
package com.mydomain.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan({"com.mydomain.service"})
public class ServiceConfig {
}
You're scanning your #Service class but you have nothing in that context that gives you a CustomerDao bean available for injection so it fails with the exception you have.
There are a bunch of other things wrong with your configuration. Your DaoConfig scans both dao and service packages. This on its own is not bad, but you have all the other XConfig classes that are redundant.
Also, your web.xml configuration is going to create 2 WebConfig contexts, one for the DispatcherServlet and one for the ContextLoaderListener.
Your ContextLoaderListener should load the root context and the DispatcherServlet should load the servlet context.
For example, the DispatcherServlet should load the WebConfig as such
#EnableWebMvc
#Configuration
#Import(ControllerConfig.class)
public class WebConfig extends WebMvcConfigurerAdapter {
Note it only #Imports ControllerConfig.
Your ContextLoaderListener should load the application config as such
#Configuration
#EnableTransactionManagement
#ComponentScan({"com.mydomain.dao", "com.mydomain.service"}, ...)
public class ApplicationConfig {
// all the #Bean methods from each of your other XxxConfig classes
}
If you want to modularize it further, keep in mind that #Import only works on the #Configuration class or context that is using it, not on the context being imported.

Resources