Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'college' available - spring

my tested code
package com.annotations.annotations;
import org.springframework.stereotype.Component;
#Component("college")
public class College {
public void id() {
System.out.println("33");
}
#Configuration
public class Config {
#Bean
public College name() {
return new College();
}
}
import javax.naming.Context;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext mech=new AnnotationConfigApplicationContext(Config.class);
College lokesh=mech.getBean("college",College.class);
lokesh.id();
}
I am getting error like this
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'college' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:872)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1160)
at com.annotations.annotations.App.main(App.java:15)

You must specify the bean name
#Bean(name = "college")
public College name() {
return new College();
}

Related

How to inject parent primitive type property through child class constructor when componentscan is enabled

I have a parent class Car & a sub class Axio. So, i'm trying to pass an argument through super("Axio") within child constructor to constructor parameter in the parent class which then assign the value into a property defined within the parent class. When i try executing the application in spring boot it throws me an exception stating
Description:
Field car in com.test.efshop.controller.HelloController required a bean of type 'com.test.efshop.Axio' that could not be found.
Action:
Consider defining a bean of type 'com.test.efshop.Axio' in your configuration.
Can anyone please tell me how to achieve this in spring boot?. My Code is as below,
// Car class
package com.test.efshop;
public class Car {
private String carName;
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public Car(String carName) {
this.carName = carName;
}
public String print() {
return "Car name is : "+carName;
}
}
//sub class of car class which is Axio
package com.test.efshop;
public class Axio extends Car{
public Axio() {
super("Axio");
}
}
//main method
package com.test.efshop;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
//controller class
package com.test.efshop.controller;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.test.efshop.Axio;
import com.test.efshop.Engine;
#Controller
public class HelloController {
#Autowired
private Axio car;
#RequestMapping(value = "/hello")
public ModelAndView print() {
return new ModelAndView("index");
}
//This is the method which i used to return the value of Car class
#RequestMapping(value = "/hello2")
#ResponseBody
public String print2() {
return car.print();
}
}
As pvpkiran commented, you can't #Autowire a class if it's not a Spring bean.
Option a) you convert the Axio class into a service or component.
#Component
public class Axio extends Car {
public Axio() {
super("Axio");
}
}
Option b) you define a bean of type Axio.
#SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean
public Axio myAxioBean() {
return new Axio();
}
}

SFTP : BeanPostProcessor interfere with #ServiceActivator and #MessagingGateway

It seems BeanPostProcessor interface implementation is having impact on #ServiceActivator. What should be the way to use BeanPostProcessor with #ServiceActivator. Thanks.
Complete logs are available here logs
Following is Java Config used for SFTP -
package com.ftp.example;
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.file.FileNameGenerator;
import org.springframework.integration.file.remote.session.CachingSessionFactory;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.integration.sftp.outbound.SftpMessageHandler;
import org.springframework.integration.sftp.session.DefaultSftpSessionFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import com.jcraft.jsch.ChannelSftp.LsEntry;
#Configuration
#EnableScheduling
#EnableAspectJAutoProxy
#EnableAsync
#IntegrationComponentScan
#EnableIntegration
#EnableBatchProcessing
#PropertySource("file:C:\\DEV\\workspace_oxygen\\ftp-example\\ftp-example.properties")
public class DependencySpringConfiguration {
private Logger LOG = LoggerFactory.getLogger(DependencySpringConfiguration.class);
#Value("${project.name}")
private String applicationName;
#Value("${${project.name}.ftp.server}")
private String server;
#Value("${${project.name}.ftp.port}")
int port;
#Value("${${project.name}.ftp.username}")
private String username;
#Value("${${project.name}.ftp.password}")
private String password;
#Value("${${project.name}.ftp.remote.directory}")
private String remoteDirectory;
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public ProcessStarter processStarter() {
return new ProcessStarter();
}
/* #Bean
public LogInjector logInjector() {
return new LogInjector();
}*/
#Bean
public FTPOutService fTPOutService() {
return new FTPOutService();
}
#Bean
public SessionFactory<LsEntry> sftpSessionFactory() {
DefaultSftpSessionFactory sf = new DefaultSftpSessionFactory();
sf.setHost(server);
sf.setPort(port);
sf.setUser(username);
sf.setPassword(password);
sf.setAllowUnknownKeys(true);
return new CachingSessionFactory<LsEntry>(sf);
}
#Bean
#ServiceActivator(inputChannel = "toSftpChannel")
public MessageHandler handler() {
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());
handler.setRemoteDirectoryExpression(new LiteralExpression(remoteDirectory));
handler.setFileNameGenerator(new FileNameGenerator() {
#Override
public String generateFileName(Message<?> message) {
return "fileNameToBeFtp.txt";
}
});
return handler;
}
#MessagingGateway
public interface MyGateway {
#Gateway(requestChannel = "toSftpChannel")
void sendToSftp(File file);
}
}
And We are calling gateway object like this while doing SFTP
Main class
public class FtpExample {
public static String[] ARGS;
private static final Logger LOG = LoggerFactory.getLogger(FtpExample.class);
public static void main(String[] args) throws Exception {
ARGS = args;
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DependencySpringConfiguration.class);
ProcessStarter processStarter = ctx.getBean(ProcessStarter.class);
processStarter.startService();
}
}
Other classes -
public class ProcessStarter {
#Inject
private FTPOutService ftpOutService;
public void startService() {
ftpOutService.ftpToBbg();
}
}
public class FTPOutService {
private static Logger log = LoggerFactory.getLogger(FTPOutService.class);
#Inject
private ApplicationContext appContext;
public void ftpToBbg() {
log.info("Starting FTP out process...");
File file = null;
try {
file = new File("C:\\Temp\\log\\debug\\ftp\\priceindex\\for-upload\\ftp-example.txt.REQ");
MyGateway gateway = appContext.getBean(MyGateway.class);
gateway.sendToSftp(file);
log.info("File {} written successfully on remote server", file);
} catch (Exception e) {
log.error("Error while uploading file {}", file, e);
}
}
}
Above code is working fine unless I am not adding following bean declaration in above defined Java Config -
public LogInjector logInjector() {
return new LogInjector();
}
Above bean definition is having following implementation -
public class LogInjector implements BeanPostProcessor {
#Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
#Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
#Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
// make the field accessible if defined private
ReflectionUtils.makeAccessible(field);
if (field.getAnnotation(Log.class) != null) {
if (org.slf4j.Logger.class == field.getType()) {
org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(bean.getClass());
field.set(bean, log);
} else if (java.util.logging.Logger.class == field.getType()) {
java.util.logging.Logger log = java.util.logging.Logger.getLogger(bean.getClass().toString());
field.set(bean, log);
}
}
}
});
return bean;
}
}
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
#Documented
public #interface Log {
}
Once any BeanPostProcessor implementation is added in Java Config, it creates problem and application not able to see toSftpChannel -
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'toSftpChannel' available at
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:685)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1199)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at
org.springframework.integration.support.channel.BeanFactoryChannelResolver.resolveDestination(BeanFactoryChannelResolver.java:88)
at
org.springframework.integration.support.channel.BeanFactoryChannelResolver.resolveDestination(BeanFactoryChannelResolver.java:45)
at
org.springframework.integration.gateway.MessagingGatewaySupport.getRequestChannel(MessagingGatewaySupport.java:327)
at
org.springframework.integration.gateway.MessagingGatewaySupport.send(MessagingGatewaySupport.java:368)
at
org.springframework.integration.gateway.GatewayProxyFactoryBean.invokeGatewayMethod(GatewayProxyFactoryBean.java:477)
at
org.springframework.integration.gateway.GatewayProxyFactoryBean.doInvoke(GatewayProxyFactoryBean.java:429)
at
org.springframework.integration.gateway.GatewayProxyFactoryBean.invoke(GatewayProxyFactoryBean.java:420)
at
org.springframework.integration.gateway.GatewayCompletableFutureProxyFactoryBean.invoke(GatewayCompletableFutureProxyFactoryBean.java:65)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy57.sendToSftp(Unknown Source)
Looks what you have:
#Bean
public LogInjector logInjector() {
return new LogInjector();
}
If you declare BeanPostProcessors as #Bean you have to specify them with the static modifier: https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/core.html#beans-factorybeans-annotations
You may declare #Bean methods as static, allowing for them to be called without creating their containing configuration class as an instance. This makes particular sense when defining post-processor beans, e.g. of type BeanFactoryPostProcessor or BeanPostProcessor, since such beans will get initialized early in the container lifecycle and should avoid triggering other parts of the configuration at that point.

How to get Neo4jTemplate in SDN4

I am using Spring Data Neo4j 4(SDN4) from the example project SDN4-northwind(https://github.com/amorgner/sdn4-northwind),when I try to get the Neo4jTemplate bean,I get the error message like this.
Does anyone know how to get the Neo4jTemplate bean from SDN4?
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.neo4j.template.Neo4jTemplate] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:371)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:968)
at org.neo4j.example.northwind.Run.main(Run.java:34)
Here is the Configuration file
package org.neo4j.example.northwind;
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.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("org.neo4j.example.northwind.repository")
#EnableTransactionManagement
public class AppContext extends Neo4jConfiguration {
public static final String NEO4J_HOST = "http://localhost:";
public static final int NEO4J_PORT = 7474;
#Override
public SessionFactory getSessionFactory() {
System.setProperty("username", "neo4j");
System.setProperty("password", System.getProperty("password","osp"));
return new SessionFactory("org.neo4j.example.northwind.model");
}
#Bean
#Override
public Neo4jServer neo4jServer() {
return new RemoteServer(NEO4J_HOST + NEO4J_PORT);
}
#Bean
#Override
//#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
return super.getSession();
}
}
Assdd
#Bean
public Neo4jOperations getNeo4jTemplate() throws Exception {
return new Neo4jTemplate(getSession());
}
to AppContext and then #Autowired Neo4jOperations neo4jTemplate;

Guice Jersey ClientConfig MessageBodyWriters and Injection

I'm trying to get Guice injection working with a Jersey MessageBodyReader/MessageBodyWriter from the client perspective. I have the server starting up properly with Guice. My issue is with the client.
I whipped together the following which demonstrates the error: SEVERE: Missing dependency for constructor public FooExample$FooReader(FooExample$FooUnmarshaller) at parameter index 0
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.MessageBodyReader;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
class FooExample {
public static void main(String[] args) {
Injector i = Guice.createInjector(new FooExample().new FooModule());
WebResource service = i.getInstance(WebResource.class);
service.path("bar")
.accept(MediaType.APPLICATION_XML)
.put(String.class, "test123");
}
public class FooModule extends AbstractModule{
#Override
protected void configure() {
bind(FooUnmarshaller.class).to(SimpleFooUnmarshaller.class);
}
#Provides
public WebResource configuredClient() {
ClientConfig config = new DefaultClientConfig();
config.getClasses().add(FooReader.class);
return Client.create(config).resource(
UriBuilder.fromUri("http://localhost:8080/foo").build());
}
}
public static class Foo {}
public static interface FooUnmarshaller {
public Foo unmarshall(InputStream is);
}
public static class SimpleFooUnmarshaller implements FooUnmarshaller {
#Override
public Foo unmarshall(InputStream is) {
return new Foo();
}
}
public static class FooReader implements MessageBodyReader<Foo> {
private final FooUnmarshaller marshaller;
#Inject
public FooReader(FooUnmarshaller marshaller) {
this.marshaller = marshaller;
}
#Override
public boolean isReadable(
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType) {
return true;
}
#Override
public Foo readFrom(
Class<Foo> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
return marshaller.unmarshall(entityStream);
}
}
}
Where I get console output:
Oct 23, 2012 3:17:22 PM com.sun.jersey.spi.inject.Errors processErrorMessages
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for constructor public FooExample$FooReader(FooExample$FooUnmarshaller) at parameter index 0
Exception in thread "main" com.google.inject.ProvisionException: Guice provision errors:
1) Error in custom provider, com.sun.jersey.spi.inject.Errors$ErrorMessagesException
at FooExample$FooModule.configuredClient(FooExample.java:40)
while locating com.sun.jersey.api.client.WebResource
1 error
at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:987)
at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1013)
at FooExample.main(FooExample.java:25)
Caused by: com.sun.jersey.spi.inject.Errors$ErrorMessagesException
at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
at com.sun.jersey.api.client.Client.<init>(Client.java:187)
at com.sun.jersey.api.client.Client.<init>(Client.java:170)
at com.sun.jersey.api.client.Client.create(Client.java:679)
at FooExample$FooModule.configuredClient(FooExample.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.google.inject.internal.ProviderMethod.get(ProviderMethod.java:104)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
at com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:978)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1024)
at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:974)
... 2 more
I have the feeling I need to use GuiceComponentProviderFactory, but I cant seem to find any documentation on it nor IoCComponentProviderFactory with ClientConfig. Any help would be much appreciated. Thanks!
So I solved my own question by guess and check. I cant confirm that this was the intended way to do things, but this works.
The Client class has a method: public static Client create(ClientConfig cc, IoCComponentProviderFactory provider) that I passed a GuiceComponentProviderFactory to and things worked out. A working version of the above code is:
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.MessageBodyReader;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.core.DefaultResourceConfig;
import com.sun.jersey.core.spi.component.ioc.IoCComponentProviderFactory;
import com.sun.jersey.guice.spi.container.GuiceComponentProviderFactory;
class FooExample {
public static void main(String[] args) {
WebResource service = configuredClient();
service.path("bar")
.accept(MediaType.APPLICATION_XML)
.put(String.class, "test123");
}
private static WebResource configuredClient() {
DefaultClientConfig config = new DefaultClientConfig();
config.getClasses().add(FooReader.class);
return Client.create(config, provider()).resource(
UriBuilder.fromUri("http://localhost:8080/foo").build());
}
private static IoCComponentProviderFactory provider() {
return new GuiceComponentProviderFactory(
new DefaultResourceConfig(),
Guice.createInjector(new FooExample().new FooModule()));
}
public class FooModule extends AbstractModule {
#Override
protected void configure() {
bind(FooUnmarshaller.class).to(SimpleFooUnmarshaller.class);
}
}
public static class Foo {}
public static interface FooUnmarshaller {
public Foo unmarshall(InputStream is);
}
public static class SimpleFooUnmarshaller implements FooUnmarshaller {
#Override
public Foo unmarshall(InputStream is) {
return new Foo();
}
}
public static class FooReader implements MessageBodyReader<Foo> {
private final FooUnmarshaller marshaller;
#Inject
public FooReader(FooUnmarshaller marshaller) {
this.marshaller = marshaller;
}
#Override
public boolean isReadable(
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType) {
return true;
}
#Override
public Foo readFrom(
Class<Foo> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
return marshaller.unmarshall(entityStream);
}
}
}
and outputs
Oct 23, 2012 5:17:11 PM com.sun.jersey.guice.spi.container.GuiceComponentProviderFactory getComponentProvider
INFO: Binding FooExample$FooReader to GuiceInstantiatedComponentProvider
Exception in thread "main" com.sun.jersey.api.client.UniformInterfaceException: PUT http://localhost:8080/foo/bar returned a response status of 404 Not Found
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:686)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.put(WebResource.java:537)
at FooExample.main(FooExample.java:28)
meaning the guice bindings worked! =)

NoSuchBeanDefinitionException: No matching bean of type

I'm trying some code.
It is an architecture Hibernate - JPA - Spring. For now, I will wish to run it in a JUnit test.
For moment, i have some exception :
GRAVE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#6295eb] to prepare test instance [test.service.UserAccountServiceTest#609959]
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userAccountService': Injection of autowired dependencies failed;
...
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private test.persistence.dao.UserAccountDao test.service.impl.UserAccountServiceImpl.userAccountDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [test.persistence.dao.UserAccountDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [test.persistence.dao.UserAccountDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
... 43 more
20 juil. 2012 10:56:19 test.service.UserAccountServiceTest tearDownOnce
INFO: tearDownOnce()
Here the JUnit : UserServiceTest
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import test.jndi.ContextDatasourceCreator;
import test.persistence.entity.UserAccount;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {
"classpath:/spring/applicationContext.xml"})
public class UserAccountServiceTest extends Assert {
private static final Log LOG = LogFactory.getFactory().getInstance(UserAccountServiceTest.class);
#Autowired
#Qualifier("userAccountService")
private UserAccountService userAccountService;
#BeforeClass
public static void setUpOnce() {
LOG.info("setUpOnce()");
ContextDatasourceCreator.init();
}
#AfterClass
public static void tearDownOnce() {
LOG.info("tearDownOnce()");
}
#Before
public void onSetUp() {
LOG.info("onSetUp()");
}
#After
public void OnTearDown() {
LOG.info("OnTearDown()");
}
#Test
public void testListAll() {
List<UserAccount> allUserAccounts = userAccountService.getAllAccounts();
for (UserAccount userAccount : allUserAccounts) {
LOG.info(userAccount);
}
}
}
/ Here my applicationContext /
<!-- Annotations Scan -->
<context:annotation-config/>
<context:component-scan base-package="test.service, test.persistence" />
<!-- Entity Manager Factory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="dbrefPU" />
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Transaction Annotations -->
<tx:annotation-driven proxy-target-class="true" />
<tx:annotation-driven transaction-manager="transactionManager" />
/ Here my source code /
GenericDao Interface :
import java.util.List;
public interface GenericDao<T extends Object> {
T save(T pojo);
void remove(Class<T> classe, int id);
void delete(T pojo);
T findById(Class<T> classe, int id);
List<T> findAll(Class<T> classe);
List<T> findByQuery(String jpql);
}
Dao Interface :
import test.persistence.entity.UserAccount;
public interface UserAccountDao extends GenericDao<UserAccount> {
UserAccount findAccount(String matricule);
}
GenericDao Impl :
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import test.persistence.dao.GenericDao;
public abstract class GenericDaoImpl<T extends Object> implements GenericDao<T> {
#PersistenceContext
protected EntityManager em;
public T save(T pojo) {
return em.merge(pojo);
}
public void remove(Class<T> classe, int id) {
T pojo = findById(classe, id);
if (pojo != null) {
em.remove(pojo);
}
}
public void delete(T pojo) {
em.remove(pojo);
}
public T findById(Class<T> classe, int id) {
return (T) em.find(classe, id);
}
public List<T> findAll(Class<T> classe) {
StringBuffer jpql = new StringBuffer(20);
jpql.append("from ").append(classe.getName());
List<T> result = em.createQuery(jpql.toString()).getResultList();
return result;
}
public List<T> findByQuery(String jpql) {
List<T> result = em.createQuery(jpql).getResultList();
return result;
}
}
Dao Impl :
import javax.persistence.NoResultException;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import test.persistence.dao.UserAccountDao;
import test.persistence.entity.UserAccount;
#Repository("userAccountDao")
public class UserAccountDaoImpl extends GenericDaoImpl<UserAccount> implements UserAccountDao {
public UserAccount findAccount(String matricule) {
Query query = em.createNamedQuery("UserAccount.login");
query.setParameter("matricule", matricule);
UserAccount account = null;
try {
account = (UserAccount) query.getSingleResult();
} catch (NoResultException nre) {
}
return account;
}
}
Service interface :
import java.util.List;
import test.persistence.entity.UserAccount;
public interface UserAccountService {
public abstract UserAccount login(String matricule);
public abstract UserAccount register(String matricule);
public abstract UserAccount getAccountWithId(Integer id);
public abstract List<UserAccount> getAllAccounts();
}
Service Impl :
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import test.persistence.dao.UserAccountDao;
import test.persistence.entity.UserAccount;
import test.service.UserAccountService;
#Service("userAccountService")
#Transactional
public class UserAccountServiceImpl implements UserAccountService {
#Autowired
#Qualifier("userAccountDao")
private UserAccountDao userAccountDao;
public UserAccount getAccountWithId(Integer id) {
return userAccountDao.findById(UserAccount.class, id);
}
public UserAccount login(String matricule) {
return userAccountDao.findAccount(matricule);
}
public UserAccount register(String matricule) {
UserAccount account = new UserAccount();
account.setMatricule(matricule);
try {
account = userAccountDao.save(account);
} catch (Exception e) {
}
return account;
}
public List<UserAccount> getAllAccounts() {
return userAccountDao.findAll(UserAccount.class);
}
}
Any idea ?
Thanks a lot !!
I didn't find the solution.
In Maven, it is not working.
In dynamic web project, i succeed to execute my test if i change the #PersistenceContext to an EXTENDED.

Resources