i have some problems with configuring Spring MVC. I made a maven multi module project with the following modules:
/api
/domain
/repositories
/webapp
I like to share the domain and the repositories between the api and the webapp (both web projects). First i want to configure the webapp to use the repositories module so i added the dependencies in the xml file like this:
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>domain</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>repositories</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
And my controller in the webapp module looks like this:
package com.mywebapp.webapp;
import com.mywebapp.domain.Person;
import com.mywebapp.repositories.services.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
#Configuration
#ComponentScan("com.mywebapp.repositories")
public class PersonController {
#Autowired
PersonService personservice;
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
Person p = new Person();
p.age = 23;
p.firstName = "John";
p.lastName = "Doe";
personservice.createNewPerson(p);
model.addAttribute("message", "Hello world!");
return "index";
}
}
In my webapp module i try to load configuration files in my web.xml like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/META-INF/persistence-context.xml, classpath:/META-INF/service-context.xml</param-value>
</context-param>
These files cannot be found so i get the following error:
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [META-INF/persistence-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [META-INF/persistence-context.xml] cannot be opened because it does not exist
These files are in the repositories module so my first question is how can i make Spring to find these files?
I also have trouble Autowiring the PersonService to my Controller class did i forget to configure something in my XML?
Here is the error message:
[INFO] [talledLocalContainer] SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
[INFO] [talledLocalContainer] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mywebapp.repositories.repository.PersonRepository com.mywebapp.repositories.services.PersonServiceImpl.personRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mywebapp.repositories.repository.PersonRepository] 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)}
PersonServiceImple.java:
package com.mywebapp.repositories.services;
import com.mywebapp.domain.Person;
import com.mywebapp.repositories.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
#Service
public class PersonServiceImpl implements PersonService{
#Autowired
public PersonRepository personRepository;
#Autowired
public MongoTemplate personTemplate;
#Override
public Person createNewPerson(Person person) {
return personRepository.save(person);
}
}
PersonService.java
package com.mywebapp.repositories.services;
import com.mywebapp.domain.Person;
public interface PersonService {
Person createNewPerson(Person person);
}
PersonRepository.java:
package com.mywebapp.repositories.repository;
import com.mywebapp.domain.Person;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.math.BigInteger;
#Repository
public interface PersonRepository extends MongoRepository<Person, BigInteger> {
}
persistance-context.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:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation=
"http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<context:property-placeholder location="classpath:mongo.properties"/>
<mongo:mongo host="${mongo.host}" port="${mongo.port}" id="mongo">
<mongo:options
connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
auto-connect-retry="${mongo.autoConnectRetry}"
socket-keep-alive="${mongo.socketKeepAlive}"
socket-timeout="${mongo.socketTimeout}"
slave-ok="${mongo.slaveOk}"
write-number="1"
write-timeout="0"
write-fsync="true"/>
</mongo:mongo>
<mongo:db-factory dbname="person" mongo-ref="mongo" id="mongoDbFactory"/>
<bean id="personTemplate" name="personTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
<mongo:repositories base-package="com.mywebapp.repositories.repository" mongo-template-ref="personTemplate">
<mongo:repository id="personRepository" repository-impl-postfix="PersonRepository" mongo-template-ref="personTemplate" create-query-indexes="true"/>
</mongo:repositories>
Thanks
Related
Am using JDK 1.8 and Spring Boot 1.2.0 RELEASE.
My pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sampleapp</groupId>
<artifactId>sampleapp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.0.RELEASE</version>
</parent>
<name>Spring Boot Security Example</name>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- HSQLDB -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
</dependencies>
</project>
My main app:
package com.sampleapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
My SecurityConfig file:
package com.sampleapp.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/public/**").permitAll()
.antMatchers("/users/**").hasAuthority("ADMIN")
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.usernameParameter("email")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("remember-me")
.logoutSuccessUrl("/")
.permitAll()
.and()
.rememberMe();
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
}
There's other classes and interfaces in my sample app but I wanted to keep this post as simple and straightfoward as possible.
When I run this using:
mvn spring-boot:run
Receive the following exceptions:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans. factory.BeanCreationException: Could not autowire field: private org.springframework.security.core.userdetails.UserDetailsService com.sampleapp.config.SecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] 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)}
... 52 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.core.userdetails.UserDetailsService com.sampleapp.config.SecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] 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:558)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 74 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] 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:530)
... 76 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.751 s
What am I possibly doing wrong? I checked out this code from:
http://kielczewski.eu/2014/12/spring-boot-security-application/
The only thing I changed was the name of the app to sampleapp along with some packages (namespaces)...
His code works but I wonder why mine doesn't?
EDITED ( for David Hernandez's question):
David, thanks for commenting, I am not sure if I understand your question because the SecurityConfig file uses the org.springframework.security.core.userdetails.UserDetailsService from Spring... In the code that I copied, there is a CurrentUserDetailsService that implements UserDetailService from Spring. If this was your question, here's the code:
package com.sampleapp.service.currentuser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.sampleapp.domain.CurrentUser;
import com.sampleapp.domain.User;
import com.sampleapp.service.user.UserService;
public class CurrentUserDetailsService implements UserDetailsService {
private static final Logger LOG = LoggerFactory.getLogger(CurrentUserDetailsService.class);
private final UserService userService;
#Autowired
public CurrentUserDetailsService(UserService userService) {
this.userService = userService;
}
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
LOG.debug("Authenticating user with email={}", email.replaceFirst("#.*", "#***"));
User user = userService.getUserByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException(String.format("User with email=%s was not found", email)));
return new CurrentUser(user);
}
}
Happy programming!
You need to be sure that you Application.java is in the root of the project
If you refactored the packages
you should have something like that
com
-sampleapp
--other packages
Application.java
By default spring boot use #ComponentScan and scan at the root of the project
If you have something outside your com.sampleapp the #ComponeScan won't be able to see it
You can add your #ComponentScan with your base packages
Ex.
#ComponentScan( basePackages = {"package containing UserDetailsService", "packages containing your app"} )
In your case the ComponentScan is not finding the components so I think it is scanning in the wrong place
Got it working... I was missing #Service for my Service classes.
I am trying to build a restful web service with Spring Boot, Maven, and Tomcat.
When I try to deploy maven jar file to Tomcat I receive this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'selectConfRoomController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate hello.SelectConfRoomController.jt; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] 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:293)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at hello.Application.main(Application.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate hello.SelectConfRoomController.jt; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] 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:509)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:290)
... 22 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] 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:1118)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:967)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:481)
... 24 common frames omitted
My application.properties file is in package src/main/resources
spring.datasource.url=jdbc:jtds:sqlserver://***
spring.datasource.username=***
spring.datasource.password=***
spring.datasource.driverClassName=net.sourceforge.jtds.jdbc.Driver
src/main/java
Application.java
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Querying...
package hello;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class SelectConfRoomController extends JdbcTemplate{
#Autowired
private JdbcTemplate jt;
#RequestMapping(value="/", method=RequestMethod.GET)
public List<Region> getRegions(){
String sql = "SELECT OUID_Region, RegionName FROM Region";
List <Region> rows = jt.query(sql,
new RowMapper<Region>(){
#Override
public Region mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Region(rs.getLong("OUID_Region"), rs.getString("RegionName"));
}
});
System.out.println("querying regions");
return rows;
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>***</groupId>
<artifactId>webservice-test</artifactId>
<version>1</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
</dependencies>
<properties>
<start-class>hello.Application</start-class>
<java.version>1.8</java.version>
</properties>
<build>
<finalName>ConfRoom</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>http://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>http://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Reading the solutions in this, I'm under the impression that I would not need an xml file. Can someone find an error that I'm not aware of? I am very new to all this so any expertise/guidance would be appreciated.
I think, the problem is, that you extend the JdbcTemplate. Spring Boot only creates a JdbcTemplate, if no other bean with this type is found. But your class is a bean of type JdbcTemplate, so the autoconfiguration for the JdbcTemplate is skipped. Try to remove the "extends JdbcTemplate", it doesn't seem to be required for your class.
You need to specify the JDBCTemplate in context xml like below or you need to add the package for component scan.
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html
<bean id="jtDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="*******"/>
<property name="url" value="*******"/>
<property name="username" value="*****"/>
<property name="password" value="**********"/>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="jtDataSource"/> --Incase if you are configuring data source
</bean>
Try declaring a bean with JdbcTemplate
#Bean
public DataSource getDataSource(){
/* Return the data source with proper configuration... */
}
#Autowired
public DataSource dataSource;
#Bean
public JdcTemplate getJdbcTemplate(){
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
return dataSource;
}
I would like to try embedded database for testing my DAO objects in Spring application.
In application context I have this tag:
<jdbc:embedded-database id="dataSourceEmbedded" type="HSQL">
<jdbc:script location="classpath:/embeddeddb/schema.sql" />
<jdbc:script location="classpath:/embeddeddb/data.sql" />
</jdbc:embedded-database>
my JUnit test class needs to work with this bean:
import org.apache.log4j.Logger;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/applicationContext.xml")
public class PartnerDAOTest {
#Autowired
#Qualifier("dataSourceEmbedded")
public EmbeddedDatabase dataSourceEmbedded;
#Test
public void testSavePartner() {
}
}
everything works ("dataSourceEmbedded" bean is created) but when I try to autowire them in PartnerDAOTest class Spring throws this exception:
testSavePartner(sandbox.PartnerDAOTest):
Error creating bean with name
'sandbox.PartnerDAOTest': Injection of
autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: public
org.springframework.jdbc.datasource.embedded.EmbeddedDatabase
sandbox.PartnerDAOTest.dataSourceEmbedded;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[org.springframework.jdbc.datasource.embedded.EmbeddedDatabase] 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),
#org.springframework.beans.factory.annotation.Qualifier(value=dataSourceEmbedded)}
What is wrong with my code?
As #M.Deinum noticed in his comment:
There is no bean of the type EmbeddedDatabase there is a DataSource.
The embedded-database eventually creates a DataSource not an
EmbeddedDatabase.
I am attempting to autowire a repository and it refuses to work. I have been struggling with this for a week now and i cannot seem to figure it out. What is funny is that when i comment out the autowiring of the person repository the program works and compiles correctly but as soon as I attempt to autowire the person repository i get this error (i have omitted most of the error because I cannot post all of it) Here is the exception, my classes are below it.
HTTP Status 500 - Servlet.init() for servlet appServlet threw exception
type Exception report
message Servlet.init() for servlet appServlet threw exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet appServlet threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
java.lang.Thread.run(Thread.java:722)
root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mycompany.smsdatabase.service.PersonImport com.mycompany.smsdatabase.controller.HomeController.personImport; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personImport': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.smsdatabase.repositories.PersonRepository com.mycompany.smsdatabase.service.PersonImport.PersonRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mycompany.smsdatabase.repositories.PersonRepository] 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)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
java.lang.Thread.run(Thread.java:722)
Here are the classes I am working with.
package com.mycompany.smsdatabase.controller;
import com.mycompany.smsdatabase.service.PersonImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#Autowired
PersonImport personImport;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String Home()
{
personImport.doImportPerson("anthony");
return "index";
}
}
package com.mycompany.smsdatabase.service;
import com.mycompany.smsdatabase.domain.Person;
import com.mycompany.smsdatabase.repositories.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class PersonImport {
#Autowired
private PersonRepository PersonRepository;
public Person doImportPerson( String id)
{
Person person = PersonRepository.findById(id);
if (person == null) {
person = new Person(id,"anthony");
}
PersonRepository.save(person);
System.out.println("inside doImportPerson");
return person;
}
}
package com.mycompany.smsdatabase.repositories;
import com.mycompany.smsdatabase.domain.Person;
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
public interface PersonRepository extends GraphRepository<Person>{
Person findById(String id);
}
I have omitted the person class since it is simply a node entity class.
Also Here is my Application context 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:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.mycompany.smsdatabase">
</context:component-scan>
<context:spring-configured/>
<neo4j:config storeDirectory="target/data/graph.db"/>
<neo4j:repositories base-package="com.mycompany.smsdatabase"/>
<bean id="graphDatabaseService" class="org.neo4j.test.ImpermanentGraphDatabase" destroy-method="shutdown"/>
<tx:annotation-driven mode="proxy"/>
</beans>
Your spring config is wrong:
You have <neo4j:repositories base-package="com.mycompany.smsdatabase"/> in your config
but the import in your java code reads
import com.mycompany.smsdatabase.repositories.PersonRepository;
You should correct your spring config to
<neo4j:repositories base-package="com.mycompany.smsdatabase.repositories"/>
You should define corresponding beans for the variables annotated with #AutoWired in the application context file, i.e.
<bean id="personRepository" class="com.mycompany.smsdatabase.repositories.PersonRepository"/>
<bean id="personImport" class="com.mycompany.smsdatabase.service.PersonImport"/>
I try to deploy an application which uses EJB on weblogic 10.3. I use the framework seam 2.2.0
I created an EJB project and en EAR project with workshop.
When I compile the project, I get this error:
weblogic.ejb.container.compliance.ComplianceException: No business interface, component interface or web service endpoint interface found for Session Bean Authenticator
Here is the bean code:
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.contexts.SessionContext;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.faces.Redirect;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.jboss.seam.security.crypto.BinTools;
import org.jboss.seam.security.management.IdentityManager;
import org.jboss.seam.security.management.JpaIdentityStore;
#Stateless
#Local
#Name("authenticator")
public class Authenticator {
}
And here is the exception:
weblogic.ejb.container.compliance.ComplianceException: No business interface, component interface or web service endpoint interface found for Session Bean Authenticator
at weblogic.ejb.container.compliance.SessionBeanClassChecker.checkInterfacesExist(SessionBeanClassChecker.java:177)
at weblogic.ejb.container.compliance.Ejb30SessionBeanClassChecker.checkInterfacesExist(Ejb30SessionBeanClassChecker.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at weblogic.ejb.container.compliance.EJBComplianceChecker.check(EJBComplianceChecker.java:337)
at weblogic.ejb.container.compliance.EJBComplianceChecker.checkDeploymentInfo(EJBComplianceChecker.java:286)
at weblogic.ejb.container.ejbc.EJBCompiler.complianceCheckJar(EJBCompiler.java:952)
at weblogic.ejb.container.ejbc.EJBCompiler.checkCompliance(EJBCompiler.java:920)
at weblogic.ejb.container.ejbc.EJBCompiler.doCompile(EJBCompiler.java:246)
at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:552)
at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:519)
at weblogic.ejb.container.deployer.EJBDeployer.runEJBC(EJBDeployer.java:393)
at weblogic.ejb.container.deployer.EJBDeployer.compileJar(EJBDeployer.java:715)
at weblogic.ejb.container.deployer.EJBDeployer.compileIfNecessary(EJBDeployer.java:618)
at weblogic.ejb.container.deployer.EJBDeployer.prepare(EJBDeployer.java:1154)
at weblogic.ejb.container.deployer.EJBModule.prepare(EJBModule.java:425)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:93)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:387)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:37)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:58)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:42)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:615)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:37)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:191)
at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:16)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:155)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.createAndPrepareContainer(ActivateOperation.java:197)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:89)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:217)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:723)
at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1190)
at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:248)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:159)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:157)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$000(DeploymentReceiverCallbackDeliverer.java:12)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$1.run(DeploymentReceiverCallbackDeliverer.java:45)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:516)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
at weblogic.ejb.container.compliance.EJBComplianceChecker.check(EJBComplianceChecker.java:327)
at weblogic.ejb.container.compliance.EJBComplianceChecker.checkDeploymentInfo(EJBComplianceChecker.java:286)
at weblogic.ejb.container.ejbc.EJBCompiler.complianceCheckJar(EJBCompiler.java:952)
at weblogic.ejb.container.ejbc.EJBCompiler.checkCompliance(EJBCompiler.java:920)
at weblogic.ejb.container.ejbc.EJBCompiler.doCompile(EJBCompiler.java:246)
at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:552)
at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:519)
at weblogic.ejb.container.deployer.EJBDeployer.runEJBC(EJBDeployer.java:393)
at weblogic.ejb.container.deployer.EJBDeployer.compileJar(EJBDeployer.java:715)
at weblogic.ejb.container.deployer.EJBDeployer.compileIfNecessary(EJBDeployer.java:618)
at weblogic.ejb.container.deployer.EJBDeployer.prepare(EJBDeployer.java:1154)
at weblogic.ejb.container.deployer.EJBModule.prepare(EJBModule.java:425)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:93)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:387)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:37)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:58)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:42)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:615)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:37)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:191)
at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:16)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:155)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.createAndPrepareContainer(ActivateOperation.java:197)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:89)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:217)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:723)
at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1190)
at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:248)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:159)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:157)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$000(DeploymentReceiverCallbackDeliverer.java:12)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$1.run(DeploymentReceiverCallbackDeliverer.java:45)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:516)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
>
Here is my ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar 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/ejb-jar_3_0.xsd"
version="3.0">
<interceptors>
<interceptor>
<interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
</interceptor>
</interceptors>
<assembly-descriptor>
<interceptor-binding>
<ejb-name>Authentificator<ejb-name>
<interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
</ejb-jar>
I don't understand my error.
Thanks for your help.
This happens because Weblogic is looking for an interface that Authenticator implements.
Change to:
#Stateless
#Name("authenticator")
public class Authenticator implements AuthenticatorLocal {
#Override
public void oneMethod()
{
//enter code here
}
}
#Local
public interface AuthenticatorLocal {
void oneMethod();
}
Note: the interface must have at least one overridden method, otherwise you'll get the same error again.
Happens because weblogic will search for an interface for EJB Local service:
#Stateless
#Local
#Name("authenticator")
public class Authenticator {
}
if you implement an interface, and provide it to EJB this problem is solved. Like this:
#Stateless
#Local(IAuthenticator.class)
#Name("authenticator")
public class Authenticator implements IAuthenticator{
//your business logic
}
public interface IAuthenticator {
// interface
}