#Value didn't work in my springboot project - java

I have a trouble in using #Value to inject the value in 'appliction.properties'. I created a new SpringBoot project, and profiled some properties in 'application.properties' file. But the application cannot start because of the 'dataSource' bean not created successfully. After debuging, i found the properties in 'application.properties' not load as expected.
Config class
#Configuration
public class SpringConfiguration {
#Value("${spring.datasource.url}")
private String url;
#Value("${spring.datasource.driverClassName}")
private String driverClassName;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
#Bean("dataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(DataSourceProperties properties) {
return DataSourceBuilder.create()
.type(HikariDataSource.class)
.driverClassName(driverClassName)
.url(url)
.username(username)
.password(password)
.build();
}
#Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
}
application.properties
spring.data.mongodb.uri=mongodb://localhost.27017
spring.data.mongodb.database=test
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.password=123
spring.datasource.username=root
spring.datasource.url=jdbc:mysql://localhost:3306/common_test
part of stacktrace
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Unsatisfied dependency expressed through method 'dataSourceScriptDatabaseInitializer' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/ty/SpringConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334) ~[spring-beans-5.3.8.jar:5.3.8]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.8.jar:5.3.8]
... 102 common frames omitted
Caused by: java.lang.NullPointerException: null
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:325) ~[na:1.8.0_191]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_191]
at com.zaxxer.hikari.HikariConfig.attemptFromContextLoader(HikariConfig.java:970) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.HikariConfig.setDriverClassName(HikariConfig.java:480) ~[HikariCP-4.0.3.jar:na]
at org.springframework.boot.jdbc.DataSourceBuilder$MappedDataSourceProperty.set(DataSourceBuilder.java:460) ~[spring-boot-2.5.1.jar:2.5.1]
at org.springframework.boot.jdbc.DataSourceBuilder$MappedDataSourceProperties.set(DataSourceBuilder.java:355) ~[spring-boot-2.5.1.jar:2.5.1]
at org.springframework.boot.jdbc.DataSourceBuilder.build(DataSourceBuilder.java:190) ~[spring-boot-2.5.1.jar:2.5.1]
at com.ty.SpringConfiguration.dataSource(SpringConfiguration.java:35) ~[classes/:na]
debug scene
application.properties
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ty</groupId>
<artifactId>common-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>common-test</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</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.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

ok First of all this is not the issue with #Value annotation. If you are already using #ConfigurationProperties(prefix = "spring.datasource") then you don't need to use the #Value annotation. Ii will automatically configure all the properties for you.
You can create the datasource bean simply like this. Make sure you have required dependency in you pom.xml.
#Bean("mysqldataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}

Add this annotation #PropertySource(value = "application.properties")
#Configuration
#PropertySource(value = "application.properties")
public class SpringConfiguration {
#Value("${spring.datasource.url}")
private String url;
#Value("${spring.datasource.driverClassName}")
private String driverClassName;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
#Bean("dataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(DataSourceProperties properties) {
return DataSourceBuilder.create()
.type(HikariDataSource.class)
.driverClassName(driverClassName)
.url(url)
.username(username)
.password(password)
.build();
}
#Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
}

Related

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder

I have issue with reading the values from the application.properties file and get the following errors,
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.1.7.RELEASE:run (default-cli) on project wedding-card: An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'weddingCardConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'aws.s3.access.key' in value "${aws.s3.access.key}" -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.1.7.RELEASE:run (default-cli) on project wedding-card: An exception occurred while running. null
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occurred while running. null
at org.springframework.boot.maven.AbstractRunMojo$IsolatedThreadGroup.rethrowUncaughtException (AbstractRunMojo.java:512)
at org.springframework.boot.maven.RunMojo.runWithMavenJvm (RunMojo.java:94)
at org.springframework.boot.maven.AbstractRunMojo.run (AbstractRunMojo.java:244)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:498)
at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:543)
at java.lang.Thread.run (Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'weddingCardConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'aws.s3.access.key' in value "${aws.s3.access.key}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties (AutowiredAnnotationBeanPostProcessor.java:380)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'aws.s3.access.key' in value "${aws.s3.access.key}"
The pom.xml file is provided:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wedcard</groupId>
<artifactId>wedding-card</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>wedding-card</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.16</version>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
<version>10.0.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.163</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.github.jhonnymertz</groupId>
<artifactId>java-wkhtmltopdf-wrapper</artifactId>
<version>1.1.11-RELEASE</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<!-- <resources>-->
<!-- <resource>-->
<!-- <directory>resources</directory>-->
<!-- <targetPath>${project.build.outputDirectory}</targetPath>-->
<!-- <includes>-->
<!-- <include>application.properties</include>-->
<!-- </includes>-->
<!-- </resource>-->
<!-- </resources>-->
</build>
<repositories>
<repository>
<id>spring.io</id>
<url>https://repo.spring.io/plugins-release/</url>
</repository>
</repositories>
</project>
The configuration source file is here:
#Configuration
#EnableSwagger2
#EnableScheduling
//#PropertySource(value = "classpath:application.properties")
public class WeddingCardConfiguration implements WebMvcConfigurer {
// #Value("${spring.mail.host}")
// private String smtpMailHost;
// #Value("${spring.mail.port}")
// private int smtpMailPort;
// #Value("${spring.mail.username}")
// private String mailUsername;
// #Value("${spring.mail.password}")
// private String mailPassword;
#Value("${aws.s3.access.key}")
private String awsS3AccessKey;
#Value("${aws.s3.access.secret}")
private String awsS3AccessSecret;
#Value("${aws.s3.bucket.region.name}")
private String awsBucketRegionName;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
// #Bean
// public JavaMailSender javaMailSender() {
// JavaMailSenderImpl sender = new JavaMailSenderImpl();
// Properties prop = new Properties();
// prop.put("mail.smtp.auth", "true");
// prop.put("mail.smtp.starttls.enable", "true"); //TLS
// sender.setJavaMailProperties(prop);
// sender.setHost(smtpMailHost);
// sender.setPort(smtpMailPort);
// sender.setUsername(mailUsername);
// sender.setPassword(mailPassword);
//
// return sender;
// }
#Bean
public AmazonS3 awsS3Client() {
AWSCredentials credentials = new BasicAWSCredentials(awsS3AccessKey, awsS3AccessSecret);
return AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(awsBucketRegionName)
.build();
}
}
The project has standard file structure provided:
I have tried to provide the property source information to the configuration class but still get the same error:
#Configuration
#EnableSwagger2
#EnableScheduling
#PropertySource(value = "classpath:application.properties")
public class WeddingCardConfiguration implements WebMvcConfigurer {
}
I have also tried to provide explicitly the resources info to the pom file:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>resources</directory>
<targetPath>${project.build.outputDirectory}</targetPath>
<includes>
<include>application.properties</include>
</includes>
</resource>
</resources>
</build>
I keep getting the same error. Whats the issue here and how to solve it?
ps: The email config values are commented purposefully and the error is not related to that
Check that those properties are actually defined in application.properties. There is also an application-aws.properties file, if the properties are only in that file then you will need to tell Spring Boot to enable the aws profile with SPRING_PROFILES_ACTIVE=aws, or add the aws properties with empty values in application.properties.
If no Spring Boot profile is activated, it will only use the properties defined in application.properties.
If you enable the aws profile, it will use use properties from application.properties as defaults, and then any matching properties defined in application-aws.properties will override those from application.properties if defined.
If what you are trying to do it only use those AWS properties when deployed to AWS, then you might need to make a Configuration object that holds those properties in it(which is a better practice than including properties with #Value in code), and make the AmazonS3 bean creation conditional on those properties being set.
Given that your project structure is a standard Maven structure, convention over configuration should apply and there should be no need to try and explicitly include application.properties with additional class path configuration. I.e everything under /src/main/resources should be available on the class path and to the application at runtime.
I needed to add a bean in the configuration file that would read the extra properties file,
#Bean
public PropertyPlaceholderConfigurer properties() {
final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
// ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.setIgnoreResourceNotFound(true);
final List<Resource> resourceLst = new ArrayList<Resource>();
resourceLst.add(new ClassPathResource("application.properties"));
resourceLst.add(new ClassPathResource("application-local.properties"));
ppc.setLocations(resourceLst.toArray(new Resource[]{}));
return ppc;
}
Afterwards, its working fine.

mvn clean verify fails integration tests : No qualifying bean of type

When I run mvn clean verify it fails doing integration tests but when i run the tests from intelliJ they all pass. I'm using junit 5.
This is the stack trace:
04-09-2019 15:03:44.923 [it.soluxioni.ars.ArsApplication.main()] DEBUG it.soluxioni.ars.ArsApplication.logStarting - Running with Spring Boot v2.1.7.RELEASE, Spring v5.1.9.RELEASE
04-09-2019 15:03:44.923 [it.soluxioni.ars.ArsApplication.main()] INFO it.soluxioni.ars.ArsApplication.logStartupProfileInfo - The following profiles are active: test
[WARNING]
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:543)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'comunicationController' defined in file [/home/gavino/Work/ars/target/classes/it/soluxioni/ars/controllers/ComunicationController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mailServiceImpl' defined in file [/home/gavino/Work/ars/target/classes/it/soluxioni/ars/services/MailServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1187)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:743)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:390)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1214)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1203)
at it.soluxioni.ars.ArsApplication.main(ArsApplication.java:135)
... 6 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mailServiceImpl' defined in file [/home/gavino/Work/ars/target/classes/it/soluxioni/ars/services/MailServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1187)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1658)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1217)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
This is the test class for testing OAuth2 authentication.
#SpringBootTest(classes = ArsApplication.class)
#WebAppConfiguration
#ActiveProfiles("test")
#ContextConfiguration(classes = {IntegrationTestConfiguration.class})
public class OAuthResourceServerTestIT {
private static final String CLIENT_ID = "asd";
private static final String CLIENT_SECRET = "asd";
private static final String CONTENT_TYPE = "application/json;charset=UTF-8";
private static final String NORMAL_USERNAME = "NormalUser";
private static final String ADMIN_USERNAME = "Administrator";
private static final String PASSWORD = "asd";
private MockMvc mvc;
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private OAuth2ClientRepository clientRepository;
#Autowired
PasswordEncoder passwordEncoder;
#Autowired
private WebApplicationContext webapp;
#BeforeEach
public void before() {
mvc = MockMvcBuilders.webAppContextSetup(webapp)
.apply(SecurityMockMvcConfigurers.springSecurity())
.alwaysDo(MockMvcResultHandlers.print())
.build();
....
//in memory db setup
}
#AfterEach
public void tearDown() {
...
//clean up db
}
#Test
public void passwordGrant() throws Exception {
final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "password");
params.add("username", ADMIN_USERNAME);
params.add("password", PASSWORD);
params.add("scope", "read");
ResultActions result = mvc.perform(MockMvcRequestBuilders.post("/oauth/token")
.params(params)
.with(SecurityMockMvcRequestPostProcessors.httpBasic(CLIENT_ID, CLIENT_SECRET))
.accept(CONTENT_TYPE))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE));
}
#Test
public void testPublicResourceWithAnonymousUser() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/public/hello")).andExpect(MockMvcResultMatchers.status().isOk());
}
......
//other tests
private String obtainAccessToken(String username, String password) throws Exception {
final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "password");
params.add("username", username);
params.add("password", password);
params.add("scope", "read");
ResultActions result = mvc.perform(MockMvcRequestBuilders.post("/oauth/token")
.params(params)
.with(SecurityMockMvcRequestPostProcessors.httpBasic(CLIENT_ID, CLIENT_SECRET))
.accept(CONTENT_TYPE));
String resultString = result.andReturn().getResponse().getContentAsString();
JacksonJsonParser jsonParser = new JacksonJsonParser();
return jsonParser.parseMap(resultString).get("access_token").toString();
}
}
For testing i use an in memory h2 database
This is my test configuration:
#Configuration
#EnableTransactionManagement
public class IntegrationTestConfiguration {
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1;");
return dataSource;
}
#Bean
public JavaMailSenderImpl mailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setProtocol("smtps");
javaMailSender.setHost("smptp#test.it");
javaMailSender.setPort(465);
javaMailSender.setUsername("test#test.it");
javaMailSender.setPassword("password");
return javaMailSender;
}
}
The problem looks like spring cannot autowire a javaMailSenderImpl(i tryed also with the interface but is's the same) that is request from my service.
The service implementation:
#Service
#Primary
public class MailServiceImpl implements MailService {
private JavaMailSenderImpl javaMailSender;
public MailServiceImpl(JavaMailSenderImpl javaMailSender) {
this.javaMailSender = javaMailSender;
}
...
//methods
}
My pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>test.it</groupId>
<artifactId>myApp</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>ars</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<junit-platform-version>5.5.1</junit-platform-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<!-- <exclusions>
<exclusion>
<!– declare the exclusion here –>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
</exclusion>
</exclusions>-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</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>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.10.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.darrachequesne</groupId>
<artifactId>spring-data-jpa-datatables</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.194</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<finalName>ars</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>pre-integration-test</id>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>post-integration-test</id>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>dev</id>
<properties>
<activatedProperties>dev</activatedProperties>
</properties>
</profile>
<profile>
<id>production</id>
<properties>
<activatedProperties>production</activatedProperties>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<activatedProperties>test</activatedProperties>
</properties>
</profile>
</profiles>
</project>
I run the test with the 'test' profile.
If i run
mvn clean test-compile failsafe:integration-test
all integration test runs and pass
I think the problem is that maven starts your spring-boot web-app (without test dependencies before your tests are executed), because of:
<execution>
<id>pre-integration-test</id>
<goals>
<goal>start</goal>
</goals>
</execution>
I expect that you get the exact same error when you start your spring-boot-application with the profile test.
Would it make sense to place the IntegrationTestConfiguration in your main code and annotate it with #Profile("test")
EDIT: Or maybe you don't need your app to be started at all, please choose what works best for your case.

Error while integrating spring with hibernate

I'm trying to integrate spring with hibernate but i get this error:
[2017-10-06 05:26:14,475] Artifact spring-mvc-hibernate-example:war: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImp': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.boraji.tutorial.spring.config.AppConfig: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution. Please see server.log for more details.
Here are some files:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.boraji.tutorial.spring</groupId>
<artifactId>spring-mvc-hibernate-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- Hibernate ORM -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- Hibernate-C3P0 Integration -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<!-- JSTL Dependency -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- Servlet Dependency -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- JSP Dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.5.4-Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-alpha2</version>
</dependency>
</dependencies>
</project>
Initializer:
public class MyWebAppInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
application config:
#Configuration
#PropertySource("classpath:db.properties")
#EnableTransactionManagement
#ComponentScans(value = { #ComponentScan("com.boraji.tutorial.spring.dao"),
#ComponentScan("com.boraji.tutorial.spring.service") })
public class AppConfig {
#Autowired
private Environment env;
#Bean
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
Properties props = new Properties();
// Setting JDBC properties
props.put(DRIVER, env.getProperty("mysql.driver"));
props.put(URL, env.getProperty("mysql.url"));
props.put(USER, env.getProperty("mysql.user"));
props.put(PASS, env.getProperty("mysql.password"));
// Setting Hibernate properties
props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));
props.put(DIALECT, env.getProperty("hibernate.dialect"));
// Setting C3P0 properties
props.put(C3P0_MIN_SIZE,
env.getProperty("hibernate.c3p0.min_size"));
props.put(C3P0_MAX_SIZE,
env.getProperty("hibernate.c3p0.max_size"));
props.put(C3P0_ACQUIRE_INCREMENT,
env.getProperty("hibernate.c3p0.acquire_increment"));
props.put(C3P0_TIMEOUT,
env.getProperty("hibernate.c3p0.timeout"));
props.put(C3P0_MAX_STATEMENTS,
env.getProperty("hibernate.c3p0.max_statements"));
factoryBean.setHibernateProperties(props);
factoryBean.setAnnotatedClasses(User.class);
return factoryBean;
}
#Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory().getObject());
return transactionManager;
}
}
db.properties:
# MySQL properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost/test
mysql.user=root
mysql.password=root
# Hibernate propert[2017-10-06 05:26:14,475] Artifact spring-mvc-hibernate-example:war: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImp': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.boraji.tutorial.spring.config.AppConfig: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution. Please see server.log for more details.ies
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQLDialect
#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150
UserDao:
#Repository
public class UserDaoImp implements UserDao {
#Autowired
private SessionFactory sessionFactory;
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}
public List<User> list() {
#SuppressWarnings("unchecked")
TypedQuery<User> query = sessionFactory.getCurrentSession().createQuery("from User");
return query.getResultList();
}
}
I saw lots of similar problems here but it didn't help. What could go wrong in my application?
DRIVER, URL, USER and PASS are all static fields. Make sure you imported all of them. Plus, make sure you imported the spring Environment (not the hibernate).
import static org.hibernate.cfg.Environment.*;
import org.springframework.core.env.Environment;

Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container;

I am getting this error when i run my spring application:
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:124)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at com.dh.test.Application.main(Application.java:13)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:174)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:147)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:121)
... 7 more
My Main Class looks like:
#Configuration
#ComponentScan
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I am trying to configure the properties of spring through java classes using #Bean:
#Configuration
#EnableJpaRepositories(
entityManagerFactoryRef = "customerEntityManager",
transactionManagerRef = "customerTransactionManager",
basePackages = {"com.dh.test.repository.customer"})
public class CustomerDbConfig {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] {"com.dh.test.model.customer"});
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalJpaProperties());
em.setPersistenceUnitName("customers");
return em;
}
Properties additionalJpaProperties(){
Properties properties = new Properties();
properties.setProperty("hibernate.ddl-auto", "update");
properties.setProperty("jdbc.dialect", "org.hibernate.dialect.MySQLDialect");
properties.setProperty("hibernate.show-sql", "true");
return properties;
}
#Bean
public DataSource dataSource(){
return DataSourceBuilder.create()
.url("jdbc:mysql://localhost:3306/customer")
.driverClassName("com.mysql.jdbc.Driver")
.username("root")
.password("root")
.build();
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory customerEntityManager){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(customerEntityManager);
return transactionManager;
}
}
extract of my POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>boot-multidb-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>boot-multidb-sample</name>
<description>Spring Boot Multiple Database Configuration</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!-- Datasource and connection pool dependencies -->
<!-- <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId>
</dependency> -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.33</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Can anyone please give a possible solution to fix this error, I tried checking the dependency hirerachy and the dependencies in my project.
It seems to me that the EmbeddedServletContainerFactory bean is not initialized. You need to kick it off:
Add the #SpringBootApplication annotation to your Application class
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(ScheduledTasks.class, args);
}
}
The #SpringBootApplication annotation contains
#Configuration
#ComponentScan
#EnableAutoConfiguration (this is the one that might fix your problem)
Also you might need to add spring-boot-starter-web dependency in your pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Sources:
Spring boot error :Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
in Your class named Application ( i.e in the class where you write SpringApplication.run("...") you have to import org.springframework.boot.autoconfigure.SpringBootApplication for the annotation #SpringBootApplication.
If you import import org.springframework.boot.SpringBootConfiguration then you will get that exception.

Trying to use my Service in 2 classes : org.springframework.beans.factory.BeanCreationException: Error creating bean with name

Trying to use my AccountService (#Service) in 2 classes getting me this Error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mz.springContextWorld.repositories.AccountRepository com.mz.springContextWorld.services.AccountService.accountRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountRepository': Cannot resolve reference to bean 'neo4jTemplate' while setting bean property 'neo4jTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.data.neo4j.config.Neo4jConfiguration#0': Cannot resolve reference to bean 'graphDatabaseService' while setting bean property 'graphDatabaseService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'graphDatabaseService': FactoryBean threw exception on object creation; nested exception is java.lang.RuntimeException: Error starting org.neo4j.kernel.EmbeddedGraphDatabase, /home/matthias/IdeaProjects/springContextWorld/target/neo4j-db-plain
here is my github repo: https://github.com/mzober/springContextWorld/tree/CollectorManager_ErrorBranch
and here is the use of my accountService:
#Autowired
AccountService accountService;
public LoginPanel() {
//errorline here
this.accountService=GuiFactory.getInstance().mainWindow().getAccountService();
init();
addComponents();
}
...
#Autowired
AccountService accountService;
public RegistryAndLoginListener() {
//no error here
accountService=GuiFactory.getInstance().mainWindow().getAccountService();
}
...getting the accountService from the context-configuration:
<context:annotation-config/>
<context:spring-configured/>
<context:component-scan base-package="com.mz.springContextWorld.domain"/>
<context:component-scan base-package="com.mz.springContextWorld.repositories"/>
<context:component-scan base-package="com.mz.springContextWorld.gui.listener"/>
<context:component-scan base-package="com.mz.springContextWorld.gui.components"/>
<context:component-scan base-package="com.mz.springContextWorld.gui.creational"/>
<context:component-scan base-package="com.mz.springContextWorld.services"/>
<neo4j:config storeDirectory="target/neo4j-db-plain"
base-package="com.mz.springContextWorld.domain"/>
<neo4j:repositories base-package="com.mz.springContextWorld.repositories"/>
<tx:annotation-driven />
... load the configuration in MainWindow (of my demo-application of Spring-Data-Neo4j)
#Autowired
public AccountService accountService;
public MainWindow() {
super(PROJECTNAME);
context= new ClassPathXmlApplicationContext("spring/spring-config.xml");
accountService=(AccountService)context.getBean("accountService");
...
}
public AccountService getAccountService(){return this.accountService;}
the AccountService:
#Service
#Transactional
public class AccountService {
#Autowired
AccountRepository accountRepository;
public AccountService(){
}
#Transactional
public Iterable<Account> getAll() {
return accountRepository.findAll();
}...
here is my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mz.springContextWorld</groupId>
<artifactId>springContextWorld</artifactId>
<packaging>jar</packaging>
<version>3.2.1.RELEASE</version>
<name>springContextWorld</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.0.7.RELEASE</spring.version>
<spring-data-neo4j.version>${project.version}</spring-data-neo4j.version>
<slf4j.version>1.7.5</slf4j.version>
<neo4j.version>2.1.5</neo4j.version>
<junit.version>4.11</junit.version>
</properties>
<repositories>
<repository>
<id>neo4j-release-repository</id>
<name>Neo4j Maven 2 release repository</name>
<url>http://m2.neo4j.org/releases</url>
</repository>
</repositories>
<dependencies>
<!--spring data-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<!--spring data end-->
<!--hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>
<!--hibernate end-->
<!--test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-kernel</artifactId>
<version>${neo4j.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<!--test end-->
<!--Loading Related dependencies ...logging-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--logging end-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
... and i'm trying to set the txmode to proxy, and more but the error is still there...
ty for helping
Seems your neo4j db has failed to start. Check last log line : Error starting org.neo4j.kernel.EmbeddedGraphDatabase, /home/matthias/IdeaProjects/springContextWorld/target/neo4j-db-plain

Categories

Resources