spring+hibernate : Injection of autowired dependencies failed - spring

i did some search but i was unable to find out what's the problem.
I'm aware the problem come from a ClassNotFoundException but i can't solve it.
error :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.it.service.applicationService com.it.controller.applicationController.applicationService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate4.LocalSessionFactoryBean] for bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate4.LocalSessionFactoryBean
caused by :
org.eclipse.jetty.servlet.ServletHolder$1: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.it.service.applicationService com.it.controller.applicationController.applicationService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate4.LocalSessionFactoryBean] for bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate4.LocalSessionFactoryBean
my conf : version : 3.2.0.RELEASE
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.0.Beta1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
i autowired everything i need to (well, i think). here is my code :
DAO class:
package com.it.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.it.model.application;
#Repository("applicationDao")
public class applicationDaoImpl implements applicationDao {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<application> listeAll() {
return sessionFactory.getCurrentSession()
.createQuery("from application").list();
}
}
Service class :
package com.it.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.it.dao.applicationDao;
import com.it.model.application;
#Service("applicationService")
public class applicationServiceImpl implements applicationService {
#Autowired
private applicationDao applicationDao;
#Transactional
public List<application> listeAll() {
return applicationDao.listeAll();
}
}
Controller class :
package com.it.controller;
import java.util.Map;
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.web.bind.annotation.RequestMapping;
import com.it.model.application;
import com.it.service.applicationService;
#Controller
#Configuration
#ComponentScan("com.it.service")
public class applicationController {
#Autowired
private applicationService applicationService;
#RequestMapping("/index")
public String listContacts(Map<String, Object> map) {
map.put("application", new application());
map.put("applicationList", applicationService.listeAll());
return "application";
}
}
spring-servlet.xml :
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:packagesToScan="com.it"
p:dataSource-ref="dataSource"
/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory"/>
<!-- Translates Hibernate exceptions to Spring Data Access Exceptions -->
<bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>
here i try several thing, localSessionFactoryBean, annotationfactorybean, hibernate 3 or 4 etc.. but none is working :(
also i have :
<context:component-scan base-package="com.it.controller" />
<context:component-scan base-package="com.it.dao" />
and services should be scanned by annotation but i tried to declare scan in xml as well.
If anyone can help me, it would be nice :)
Thanks you in advance,
Aure

You need to add spring-orm to your Maven Dependencies.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
Make sure your maven dependencies are being deployed, check out the first image in this answer: servlet packages not importing after converting project to maven project in eclipse

Where do you hand the hibernate.dialect to the sessionFactory? For a more complete view it would be helpful to see all parts of the configuration going into hibernate. So can you post your DataSource.
But what I can say so far that the hibernate.dialect is a property that is mandatory to set. Besides the DataSource it is pretty much the only really essential configuration:
<property name="hibernate.dialect">org.hibernate.dialect.GenericDialect</property>
Try adding this to your sessionFactory Bean.

Related

org.springframework.beans.factory.UnsatisfiedDependencyException Spring JPA

i need help to solve this error here, for my college project.
I created an online database and from there I tried to develop a service to be consumed later, the problem is that when I run to test the service I get these errors, I've looked in many places to try to correct them, but so far all the attempts were unsuccessful.
I would really appreciate it if someone could detect the error that is happening and help correct it.
Thank you so much. :D
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
</dependencies>
Aplication:
package com.teig.DescubraPortugal;
import com.teig.DescubraPortugal.repositories.UtilizadorRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#ComponentScan({"com.teig.DescubraPortugal.controllers","com.teig.DescubraPortugal.services","com.teig.DescubraPortugal.repositories"})
#SpringBootApplication
public class DescubraPortugalApplication {
public static void main(String[] args) {
SpringApplication.run(DescubraPortugalApplication.class, args);
}
}
Repository:
#Repository
public interface UtilizadorRepository extends JpaRepository<Utilizador, Integer> {
}
Service:
#Service
public class UtilizadorService {
#Autowired
UtilizadorRepository utilizadorRepository;
public List<Utilizador> findUsers(){
return utilizadorRepository.findAll();
}
}
Controller:
#RestController
#RequestMapping("user")
public class UtilizadorController {
#Autowired
UtilizadorService utilizasddorService;
#GetMapping("/all")
public List<Utilizador> findUsers(){
return utilizasddorService.findUsers();
}
}
Error appeared:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'utilizadorController': Unsatisfied dependency expressed through field 'utilizasddorService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'utilizadorService' defined in file [C:\Users\telmo\OneDrive\Documentos\GitHub\DescubraPortugalWS\target\classes\com\teig\DescubraPortugal\services\UtilizadorService.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.teig.DescubraPortugal.services.UtilizadorService] from ClassLoader [sun.misc.Launcher$AppClassLoader#18b4aac2]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) [spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) com.teig.DescubraPortugal.DescubraPortugalApplication.main(DescubraPortugalApplication.java:23) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'utilizadorService' defined in file [sun.misc.Launcher$AppClassLoader#18b4aac2]
Caused by: java.lang.IllegalStateException: Failed to introspect Class [com.teig.DescubraPortugal.services.UtilizadorService] from ClassLoader [sun.misc.Launcher$AppClassLoader#18b4aac2]
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.3.19.jar:5.3.19]
... 29 common frames omitted ```
Caused by: java.lang.NoClassDefFoundError: org/springframework/data/jpa/repository/JpaRepository
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_291]
at org.springframework.util.ReflectionUtils.getDeclaredFields(ReflectionUtils.java:738) ~[spring-core-5.3.19.jar:5.3.19]
... 35 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.data.jpa.repository.JpaRepository
at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_291]
Thanks Again for the help
Don't look at your model, so I created one to test your application:
package com.teig.descubraportugal.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Utilizador {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
}
The application worked normally with this model, but I used the H2 database that works in memory with a console accessible by the browser. You can configure in:
application.properties:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
pom.xml:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
to see the database http://localhost:8080/h2-console/
As the error says: Spring can't create bean utilizadorController because it needs utilizasddorService bean which Spring can't find class for.
I bet it has something to do with your custom #ComponentScan.
Try removing it or make sure your packages structure looks like this:
com.teig.DescubraPortugal
|- DescubraPortugalApplication.java
|- controllers
| |- UtilizadorController.java
|- services
| |- UtilizadorService.java
|- repositories
| |- UtilizadorRepository.java

Error creating spring boot bean - "The blank final field em may not have been initialized"

I am a newbie for the spring boot framework. I have successfully done crud operation. After that I have decided that to do Advanced search concepts. Please see the code below, which I used.
package com.lean.repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.repository.JpaRepository;
import com.lean.entity.Merchant;
public interface MerchantDao extends JpaRepository<Merchant, Long> {
EntityManager em;
public List<Merchant> findAllByNameIn(Set<String> name);
public default List<Merchant> findMerchantList(String name, String email) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Merchant> cq = cb.createQuery(Merchant.class);
Root<Merchant> book = cq.from(Merchant.class);
List<Predicate> predicates = new ArrayList<>();
if (name != null) {
predicates.add(cb.equal(book.get("name"), name));
}
if (email != null) {
predicates.add(cb.equal(book.get("email"), email));
}
cq.where(predicates.toArray(new Predicate[0]));
return em.createQuery(cq).getResultList();
};
}
Here, I am getting the below error.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'merchantDao': Invocation of init method failed; nested exception is java.lang.Error: Unresolved compilation problem:
The blank final field em may not have been initialized
When I am trying to get the"EntityManager em" entity object, I will get the above error.
Please help someone to fix the issue. Thanks in advance
Try this :-
#PersistenceContext
private EntityManager em;
Also check for below dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>

Unit Testing Freemarker templates in SpringBoot - unable to initialize freemarker configuration

we are using Freemarker for generating the HTML code for the emails our application is going to be sending.
Our usage and configuration is based off of https://github.com/hdineth/SpringBoot-freemaker-email-send
Particularly:
package com.example.techmagister.sendingemail.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
import java.io.IOException;
#Configuration
public class FreemarkerConfig {
#Bean(name="emailConfigBean")
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration(ResourceLoader resourceLoader) {
FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
bean.setTemplateLoaderPath("classpath:/templates/");
return bean;
}
}
However, there is absolutely no information or documentation anywhere, about how to run Unit Tests for this using JUnit 5.
When I added the relevant dependencies
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
versions:
<junit.jupiter.version>5.3.1</junit.jupiter.version>
<mockito.version>2.23.0</mockito.version>
And made a test class:
package com.example.techmagister.sendingemail;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
#ExtendWith({SpringExtension.class, MockitoExtension.class})
#Import(com.example.techmagister.sendingemail.config.FreemarkerConfig.class)
public class EmailTestTest {
private static final Logger LOGGER = LogManager.getLogger(EmailTestTest.class);
#Autowired
#Qualifier("emailConfigBean")
private Configuration emailConfig;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void test() throws Exception {
try {
Template template = emailConfig.getTemplate("email.ftl");
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run that in debug mode, emailConfig is null.
Why is that?
Their test example https://github.com/hdineth/SpringBoot-freemaker-email-send/blob/master/src/test/java/com/example/techmagister/sendingemail/SendingemailApplicationTests.java
works if I add the same autowired property, but it is a full SprintBoot context that is slow to boot, and I need to test just template usage, without actually sending out the email.
In our actual code (which is large, multi module project), I have another error org.springframework.beans.factory.UnsatisfiedDependencyException
caused by:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'freemarker.template.Configuration' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=emailConfigBean)}
But that is just for context, first I want to get it working in the simple, sample project then worry about getting it working in our complex one.
You cannot autowire your emailConfigBean directly as a freemarker.template.Configuration
FreeMarkerConfigurationFactoryBean is a factorybean.
To get the Confuguration you need to call factorybean.getObject()
so instead of
#Autowired
#Qualifier("emailConfigBean")
private Configuration emailConfig;
just autowire your factorybean FreeMarkerConfigurationFactoryBean and load your template with emailConfig.getObject().getTemplate("email.ftl")
#Autowired
#Qualifier("emailConfigBean")
private FreeMarkerConfigurationFactoryBean emailConfig;
#Test
void testFreemarkerTemplate(){
Assertions.assertNotNull(emailConfig);
try {
Template template =
emailConfig
.getObject() // <-- get the configuration
.getTemplate("email.ftl"); // <-- load the template
Assertions.assertNotNull(template);
} catch (Exception e) {
e.printStackTrace();
}
working test on github
On the other hand...
In a Spring Boot application the Freemarker configuration can be simplified by using the spring-boot-starter-freemarker dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
This starter for building MVC web applications using FreeMarker views adds the necessary auto-configuration. All you need to do is placing your template files in the resources/templates folder.
Then you just can autowire the freemarkerConfig (or use constructor injection):
#Autowired
private Configuration freemarkerConfig;
There is a nice example here, in the attached github code. I was able to use it as a starting point to test my freeMarker code: https://cleantestcode.wordpress.com/2014/06/01/unit-testing-freemarker-templates/

error Type referred to is not an annotation type: MyAnnotation

I am following the given documentation at Custom Spring AOP Annotation
Following are sources I have written in my project with similar dependencies as mentioned in the article.
Annotation Definition:
package com.sell.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface CommitServiceAdvice {}
Aspect definition:
package com.sell.business.service.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.sell.aggregator.MessageFlowAggregator;
#Aspect
#Component
public class CommitServiceAspect {
private Logger log = LoggerFactory.getLogger(this.getClass());
#Around(value="#annotation(CommitServiceAdvice)",argNames="mfa")
public MessageFlowAggregator advice(ProceedingJoinPoint joinPoint,MessageFlowAggregator mfa) throws Throwable {
log.debug(">>> matching advice on {}",joinPoint);
mfa= (MessageFlowAggregator) joinPoint.proceed();
log.debug("<<< returning advice on {}",joinPoint);
return mfa;
}
}
Joint Point:
package com.sell.business.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.sell.aggregator.MessageFlowAggregator;
import com.sell.annotations.CommitServiceAdvice;
import com.sell.stage.processor.StageProcessor;
#Component("commitService")
public class CommitServiceImpl implements DCSService{
#Override
#CommitServiceAdvice
public Object process(MessageFlowAggregator mfa){
return null;
}
}
pom.xml dependencies: parent pom uses: spring-boot-starter-parent version 1.5.2
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Using Springfox implementation of Swagger API -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- Swagger UI to make interaction with the Swagger-generated API documentation
easier. -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
Having all this setup done, I am getting the following exception on application startup. Since, I am new to aop am not able to understand the root cause of it.
Kindly help me here. Thanks
2018-01-31 17:47:36.416 WARN 15272 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'objectMapperConfigurer' defined in class path resource [springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error Type referred to is not an annotation type: CommitServiceAdvice
2018-01-31 17:47:36.432 ERROR 15272 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Destroy method on bean with name 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor' threw an exception
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5cdd8682: startup date [Wed Jan 31 17:47:33 IST 2018]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:253) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:961) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:968) [spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1033) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:555) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at com.DCSSell_WSApplication.main(DCSSell_WSApplication.java:17) [classes/:na]
Since your aspect and annotation are defined in different packages, you need to use the fully qualified class name of the annotation class when you reference it in your pointcut expression. Also, you want to reference a method argument named mfa, you need to specify it in the pointcut expression. The argNames annotation parameter is only required in case you're compiling without debug info and the argument names for the method representing the advice are not available.
#Around("#annotation(com.sell.annotations.CommitServiceAdvice) && args(mfa)"
/*, argNames="mfa"*/)

Could not autowire field/expected at least 1 bean which qualifies as autowire candidate

I am pretty new to Spring and although I have used it for a couple of projects before and I've seen a lot of similar questions, I can't figure out what is wrong with this exception:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public service.UserServiceI controller.ApplicationController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [service.UserServiceI] 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=userService)}
This is the relevant part of the stack trace.
Here is my controller class:
#Controller
#RequestMapping("/")
public class ApplicationController {
#Autowired
#Qualifier("userService")
public UserServiceI userService;
}
This is my UserService interface:
public interface UserService {
//methods
}
And the implementation:
#Service("userService")
public class UserServiceI implements UserService{
#Autowired
private UserDao dao;
//methods
}
Here is my XML configuration file:
<context:component-scan base-package="configuration">
</context:component-scan>
<bean id="resView" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:default-servlet-handler/>
<mvc:resources location="/resources/css/" mapping="/resources/css/*">
</mvc:resources>
<mvc:resources location="/resources/js/" mapping="/resources/js/*">
</mvc:resources>
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler />
<context:component-scan base-package="controller">
</context:component-scan>
<context:component-scan base-package="dao"></context:component-scan>
<context:component-scan base-package="model"></context:component-scan>
<context:component-scan base-package="service"
use-default-filters="true">
</context:component-scan>
This is Spring configuration:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "{configuration, controller, dao, model, service}")
public class SpringConfig extends WebMvcConfigurerAdapter{
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WebContent/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
And Hibernate configuration:
#Configuration
#EnableTransactionManagement
#ComponentScan({"configuration", "controller", "dao", "model", "service"})
#PropertySource(value = {"classpath:appProperties"})
public class HibernateConfig {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory(){
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] {"model"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
#Bean
public Properties hibernateProperties(){
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect",environment.getRequiredProperty("hibernate.dialect"));
hibernateProperties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
hibernateProperties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return hibernateProperties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
And pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
I commented the code in Controller and the result was that it was unable to autowire SessionFactory, although it is defined. Please help me!
Few things:
You should autowire the interface, and not the implementation:
#Autowired
public UserService userService;
Remove the value param being passed to the #Service in UserServiceI, unless you want to use some fancy name, otherwise Spring will use the name of the bean in lowercases automatically (remember you should be autowiring the interface);
Are you sure your packages are named only controller, dao, etc and not xxx.yyy.controller? Because if they have a prefix, your scan is incorrect here:
<context:component-scan base-package="service"
use-default-filters="true">
</context:component-scan>
3.1. Just a tip, but you can use comma to separate your packages, instead of multiple declarations:
<context:component-scan base-package="service, dao, controller, ..." />
To debug, temporarily comment :
#Autowired
#Qualifier("userService")
public UserServiceI userService;
and print all the beans loaded by spring container in your controller :
#Autowired
private ApplicationContext applicationContext;
#RequestMapping("/print")
public void print() {
String[] beanNames = applicationContext.getBeanDefinitionNames();
for (String beanName : beanNames) {
System.out.println(beanName + " : " + applicationContext.getBean(beanName).getClass().toString());
}
}
and make sure your service bean is loaded.

Resources