org.springframework.beans.factory.UnsatisfiedDependencyException Spring JPA - spring

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

Related

SpringBoot - UnsatisfiedDependencyException: Error creating bean with name 'cassandraSession'

I am trying to run my SpringBoot application to check some changes I did in one of the controllers and I am getting the following error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inboxApp': Unsatisfied dependency expressed through field 'folderRespository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'folderRepository' defined in io.inbox.folders.FolderRepository defined in #EnableCassandraRepositories declared on InboxApp: Cannot resolve reference to bean 'cassandraTemplate' while setting bean property 'cassandraTemplate'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cassandraSession' defined in class path resource [org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.datastax.oss.driver.api.core.CqlSession]: Factory method 'cassandraSession' threw exception; nested exception is com.datastax.oss.driver.api.core.DriverExecutionException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.8.jar:5.3.8]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.8.jar:5.3.8]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.2.jar:2.5.2]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.2.jar:2.5.2]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.2.jar:2.5.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.2.jar:2.5.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.2.jar:2.5.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.2.jar:2.5.2]
at io.inbox.InboxApp.main(InboxApp.java:41) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.5.2.jar:2.5.2]
To be honest, this was already happening to me since I started to build de app, but after re-running the app the error seemed to disappear and everything went well. However, since I did some minor modifications in my code I cannot run the app anymore... Could you please tell me what do you think is generating this error? As you will see, my classes are super simple and I think everything is being done properly. Thanks for your time.
InboxApp
import java.nio.file.Path;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.cass`enter code here`andra.CqlSessionBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import org.springframework.web.bind.annotation.RestController;
import com.datastax.oss.driver.api.core.uuid.Uuids;
import io.inbox.emaiList.EmailListItem;
import io.inbox.emaiList.EmailListItemKey;
import io.inbox.emaiList.EmailListItemRepository;
import io.inbox.email.Email;
import io.inbox.email.EmailRepository;
import io.inbox.folders.Folder;
import io.inbox.folders.FolderRepository;
#SpringBootApplication
#EnableCassandraRepositories
#RestController
public class InboxApp {
#Autowired
FolderRepository folderRespository;
#Autowired
EmailListItemRepository emailListItemRepository;
#Autowired
EmailRepository emailRepository;
public static void main(String[] args) {
SpringApplication.run(InboxApp.class, args);
}
#Bean
public CqlSessionBuilderCustomizer sessionBuilderCustomizer(DataStaxAstraProperties astraProperties) {
Path bundle = astraProperties.getSecureConnectBundle().toPath();
return builder -> builder.withCloudSecureConnectBundle(bundle);
}
#PostConstruct
public void init(){
folderRespository.save(new Folder("vict0rsan", "Inbox", "blue"));
folderRespository.save(new Folder("vict0rsan", "Sent", "green"));
folderRespository.save(new Folder("vict0rsan", "Important", "yellow"));
for(int i = 0; i < 10; i++){
EmailListItemKey key = new EmailListItemKey();
key.setId("vict0rsan");
key.setLabel("Inbox");
key.setTimeUUID(Uuids.timeBased());
EmailListItem item = new EmailListItem();
item.setKey(key);
item.setDestination(List.of("vict0rsan", "abc", "testingUser"));
item.setSubject("Subject: " + i);
item.setIsRead(false);
emailListItemRepository.save(item);
Email email = new Email();
email.setId(key.getTimeUUID());
email.setSender("vict0rsan");
email.setSubject("Subject:" + i);
email.setBody("Body: " + i);
email.setDestination(item.getDestination());
emailRepository.save(email);
}
}
}
FolderRepository
package io.inbox.folders;
import java.util.List;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface FolderRepository extends CassandraRepository<Folder, String>{
List<Folder> findAllById(String id);
}
FolderService
package io.inbox.folders;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
#Service
public class FolderService {
public List<Folder> fetchDefaultFolders(String userId){
return Arrays.asList(
new Folder(userId, "Inbox", "white"),
new Folder(userId, "Sent Items", "green"),
new Folder(userId, "Important", "red")
);
}
}
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>victorsan</groupId>
<artifactId>inbox-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>inbox-app</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-core</artifactId>
<version>4.13.0</version>
</dependency>
<dependency>
<groupId>org.ocpsoft.prettytime</groupId>
<artifactId>prettytime</artifactId>
<version>5.0.2.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Edit: I have found out that if I comment all the 'FolderRepository' stuff within the InboxApp, then the same error will be thrown but referring to the next #Autowired repository (in my case 'emailListItemRepository')
The sample app code you posted contains this line at the top:
import org.springframework.boot.autoconfigure.cass`enter code here`andra.CqlSessionBuilderCustomizer;
Notice it contains enter code here instead of just cassandra.
If your code really contains that line, it might be the reason your app can't create a CqlSession.
Validate your code and try to compile it again. Cheers!

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"*/)

Spring boot + MongoDB

I'm working with Spring boot + MongoDB, and I've tried to deploy this application, but I have this exception:
Caused by: java.lang.ClassNotFoundException: org.springframework.data.mongodb.repository.MongoRepository
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_111]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_111]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_111]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_111]
... 63 common frames omitted
this is my code:
POM:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
AddressDAOImpl:
package pe.com.microexample.daoimpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import pe.com.microexample.bean.Address;
import pe.com.microexample.dao.AddressDAO;
import pe.com.microexample.repository.AddressRepository;
#Repository
public class AddressDAOImpl implements AddressDAO{
#Autowired
private AddressRepository addressRepository;
}
AddressRepository:
package pe.com.microexample.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import pe.com.microexample.bean.Address;
public interface AddressRepository extends MongoRepository<Address, Integer>{
Address getAddress();
}
Any idea about this exception?
maven dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
=======================================================================
application.properties
server.port = 8080
spring.data.mongodb.database=user_db
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
=======================================================================
Repository
public interface UserRepository extends MongoRepository{
}
for reference use below link:(step by step explanation)
https://www.youtube.com/watch?v=2Tq2Q7EzhSA&t=7s

spring+hibernate : Injection of autowired dependencies failed

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.

Resources