Spring Boot 2.0.0 cycle bean dependency EntityManger and SessionFactory - java

I have problem with new Spring Boot version 2.0.0.
I need to create SessionFactory bean, for that I need Spring to inject EntityManager.
package cz.moravec;
import cz.moravec.provisioning.Provisioner;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceUnit;
#SpringBootApplication
#EntityScan("cz.moravec.data")
public class Main {
// #Bean
// public CountryDao countryDao() {
// return new CountryDao();
// }
//
// #Bean
// public TownDao townDao() {
// return new TownDao();
// }
#Autowired
#Bean
#Transactional
public SessionFactory sessionFactory(EntityManager entityManager) {
Session session = entityManager.unwrap(Session.class);
return session.getSessionFactory();
}
#Profile({"devel", "test"})
#Bean(initMethod = "doProvision")
public Provisioner provisioner() {
return new Provisioner();
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Main.class);
ApplicationContext ctx = app.run(args);
// CountryDao countryDao = ctx.getBean(CountryDao.class);
// List<Country> countries = countryDao.getCountries();
// UsersDao usersDao = ctx.getBean(UsersDao.class);
//
// List<User> users = usersDao.getAllUsers();
// System.out.println(users);
}
}
This code works when using Spring Boot 1.5.11.RELEASE. But does not with Spring Boot 2.0.0.RELEASE.
When I run code ApplicationContext is not created because of cycle dependency.
There is output from console.
19:44:31.282 [main] WARN o.s.c.a.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in cz.moravec.Main: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.orm.jpa.SharedEntityManagerCreator#0': Cannot resolve reference to bean 'sessionFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'sessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?
Disconnected from the target VM, address: '127.0.0.1:11537', transport: 'socket'
19:44:31.286 [main] INFO o.s.b.a.l.ConditionEvaluationReportLoggingListener -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
19:44:31.288 [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter -
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| sessionFactory defined in cz.moravec.Main
↑ ↓
| org.springframework.orm.jpa.SharedEntityManagerCreator#0
└─────┘
Maven 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>cz.moravec</groupId>
<artifactId>semester_project</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
</project>

Is is a MUST to set the SessionFactory as bean when init the SpringBoot application?
Another solution is to get the hibernate sessionFactory / session in your Dao classes.
Following is an example:
#Repository
public class CountryDao {
#Autowired
private EntityManagerFactory entityManagerFactory;
private Session getSessionFactory() {
return entityManagerFactory.unwrap(SessionFactory.class);
}
...
}
I can successfully get the SessionFactory in the Dao class.
But if your purpose is to only get the current Hibnerate Session object, following is a more cleaner way:
#Repository
public class CountryDao {
#Autowired
private EntityManager entityManager;
private Session getSession() {
return entityManager.unwrap(Session.class);
}
...
}
The SpringBoot i'm testing is 2.1.3.RELEASE

Related

Spring boot JNDI is not working and tomcat not getting started

I am working on spring boot application and I trying to connect datasource using JNDI but it is not working and giving me below error please help if any one knows the reason:
This is the error it is showing:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'i': Invocation of init method failed;
nested exception is org.springframework.jndi.JndiLookupFailureException: JndiObjectTargetSource failed to obtain new target object;
nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter,
or in an application resource file: java.naming.factory.initial
For the pom.xml dependency file I have included following 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-web</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.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- Added from here -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.25</version>
</dependency>
As I am using postgresql database I have used it's dependencies and in application.properties file I have mentioned as below:
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
# Datasource settings
spring.datasource.initialize=true
spring.datasource.jndi-name=jdbc/IDB
spring.jmx.enabled: false
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=ROOT
spring.datasource.type=javax.sql.DataSource
spring.datasource.separator=;
And for tomcat context naming initialization I have defined bean as below:
#Bean
public TomcatServletWebServerFactory tomcatFactory() {
return new TomcatServletWebServerFactory() {
#Override
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
tomcat.enableNaming();
try {
tomcat.addContext("/aiv/appimages", imgLoc);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.getTomcatWebServer(tomcat);
}
#Override
protected void postProcessContext(org.apache.catalina.Context context) {
ContextResource resource = new ContextResource();
resource.setName("jdbc/ActiveIDB");
resource.setType(DataSource.class.getName());
resource.setProperty("driverClassName", "org.postgresql.Driver");
resource.setProperty("url", "jdbc:postgresql://localhost:5432/postgres");
resource.setProperty("username", "postgres");
resource.setProperty("password", "ROOT");
context.getNamingResources().addResource(resource);
}
};
}
#Bean(destroyMethod="")
public DataSource dataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/IDB");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
return (DataSource)bean.getObject();
}
Please any one can let me know what is wrong am I doing why it is giving me that error. Help appriteated.
You have to do 5 things:
tomcat.enableNaming();
add ContextResource to NamingResources (use same names: jdbc/IDB and jdbc/ActiveIDB have different hash codes :) )
spring.datasource.jndi-name: jdbc/DS_NAME
add org.springframework:spring-jdbc (class EmbeddedDatabaseType) to classpath (it will activate JndiDataSourceAutoConfiguration)
at this moment, spring will try to create datasource but fails, because of org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory class is not in classpath (it's default factory for javax.sql.DataSource resource)
add dependency org.apache.tomcat:tomcat-dbcp:8.5.4 [or hier version] (it contains org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory)
package com.example;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.ContextResource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.context.annotation.Bean;
import javax.servlet.ServletException;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
#SpringBootApplication
public class Application {
/**
* Or you can copy full implementation from
* org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration.EmbeddedTomcat
* override only getTomcatWebServer(Tomcat)
* and provide TomcatContextCustomizer instead of overriding 'postProcessContext(Context)'
*/
#Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory() {
return new TomcatServletWebServerFactory() {
#Override
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
//1 enable naming
tomcat.enableNaming();
return super.getTomcatWebServer(tomcat);
}
#Override
protected void postProcessContext(Context context) {
//2 create resource
ContextResource resource = new ContextResource();
resource.setName("jdbc/h2DS");
resource.setType(DataSource.class.getName());
resource.setProperty("driverClassName", "org.h2.Driver");
resource.setProperty("url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
resource.setProperty("username", "sa");
resource.setProperty("password","");
context.getNamingResources().addResource(resource);
}
};
}
public static void main(String[] args) throws ServletException, IOException, SQLException {
//3 JndiDataSourceAutoConfiguration will provide that bean if
// a) spring.datasource.jndi-name: jdbc/h2DS
// b) org.springframework:spring-jdbc (class EmbeddedDatabaseType) is in classpath
SpringApplication.run(Application.class, args)
.getBean(DataSource.class)
.getConnection();
}
}
dependencies
org.springframework.boot:spring-boot-starter-web
org.springframework:spring-jdbc
com.h2database:h2:2.1.214 (runtime)
org.apache.tomcat:tomcat-dbcp:8.5.4 [or hier] (runtime)
application.properties
spring.datasource.jndi-name=jdbc/h2DS

REST API: Field repository in service required a bean named 'entityManagerFactory' that could not be found

I am building a REST API using spring boot with a MYSQL database, my app installs successfully but when running the main application I receive this error
2020-06-22 15:40:30.638 WARN 8412 --- [ restartedMain] ConfigServletWebServerApplicationContext :
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name
'itemController': Unsatisfied dependency expressed through field 'itemService'; nested exception
is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name
'itemService': Unsatisfied dependency expressed through field 'todoItemRepository'; nested exception
is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemRepository':
Cannot create inner bean '(inner bean)#5b270c70' of type [org.springframework.orm.jpa.SharedEntityManagerCreator]
while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name '(inner bean)#5b270c70': Cannot resolve reference to bean 'entityManagerFactory'
while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
Following are my files:
Controller:
#RestController
#RequestMapping("/todo")
public class ItemController {
#Autowired
private ItemService itemService;
//methods
}
Model:
#Entity
#Table(name = "TODO")
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "itemId")
private Long itemId;
//other variables followed by setters and getters
service:
#Service
public class ItemService {
#Autowired
private ItemRepository todoItemRepository;
public Item saveTodoItem(Item item) {
return todoItemRepository.save(item);
}
//other methods
}
Repository:
#Repository
public interface ItemRepository extends JpaRepository<Item, Long> {
Item findByItemId(Long itemId);
List<Item> findByListId(UUID listId);
}
Configuration files:
public class BasicInitialize extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {
TnDserviceApplication.class
};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[]{
null
};
}
}
persistence config:
#Configuration
#EnableTransactionManagement
#ComponentScan("com.example.TNDservice.config")
#PropertySource({"classpath:application.properties"})
public class PersistenceConfig {
// Class which call the application properties
#Autowired
private Environment env;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
bean.setDataSource(dataSource());
bean.setPackagesToScan("com.example.TNDservice.Entity");
bean.setHibernateProperties(propertiesForHibernate());
return bean;
}
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
return dataSource;
}
#Bean
Properties propertiesForHibernate() {
Properties properties = new Properties();
properties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));
properties.put("hibernate.ddl-auto", env.getRequiredProperty("hibernate.ddl-auto"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
hibernateTransactionManager.setSessionFactory(sessionFactory);
return hibernateTransactionManager;
}
}
application.propoties
jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:mysql://localhost:3306/?user=root
jdbc.username=root
jdbc.password=1234
hibernate.dialect=org.hibernate.dialect.SQLServerDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.ddl-auto=validate
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.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>TNDservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>TNDservice</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-devtools</artifactId>
<scope>runtime</scope>
</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>
</dependencies>
<pluginRepositories>
<pluginRepository>
<id>icm</id>
<name>Spring Framework Milestone Repository</name>
<url>http://maven.icm.edu.pl/artifactory/repo</url>
</pluginRepository>
</pluginRepositories>
<build>
<finalName>RESTservice</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
Appreciate any help regarding this matter! Thank you!
your dependency shows that you want to connect with mysql database.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
But, in database properties, you have provided microsoft sql DB info.
jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:mysql://localhost:3306/?user=root
jdbc.username=root
jdbc.password=1234
There is no compatibility to connect 2 diff databases.
see the diff between mysql and microsoft sql database server.
https://www.tutorialspoint.com/difference-between-mysql-and-sql-server#:~:text=Both%20MySQL%20and%20SQL%20Server,is%20licensed%20product%20of%20Microsoft.&text=SQL%20Server%20supports%20programming%20languages,Visual%20Basic%2C%20Delphi%2C%20R.

Spring Batch test fails after completion because context is not active

I have created a simple job in Spring Batch with Spring Boot to be executed as a task with Spring Cloud Task (all in STS4). If I execute it as a Spring Boot App, te execution is correct and without problems, but if I compile the project or try to launch the test, the execution of the job is correct:
o.s.c.t.b.l.TaskBatchExecutionListener : The job execution id 19 was run within the task execution 56
o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
com.example.demo.MyTasklet : Executing Tasklet: STEP 1
o.s.batch.core.step.AbstractStep : Step: [step1] executed in 16ms
o.s.batch.core.job.SimpleStepHandler : Executing step: [step2]
com.example.demo.MyTasklet : Executing Tasklet: STEP 2
o.s.batch.core.step.AbstractStep : Step: [step2] executed in 7ms
o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=job2]] completed with the following parameters: [{run.id=7, -spring.output.ansi.enabled=always}] and the following status: [COMPLETED] in 52ms
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Shutdown initiated...
com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Shutdown completed.
But after that, it happends an exception:
o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#576d5deb] to prepare test instance [com.example.demo.DemoJobApplicationTests#173ed316]
java.lang.IllegalStateException: The ApplicationContext loaded for [[MergedContextConfiguration#e350b40 testClass = DemoJobApplicationTests, locations = '{}', classes = '{class com.example.demo.DemoJobApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#5e82df6a, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#50a638b5, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#130161f7, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#479d31f3], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]] is not active. This may be due to one of the following reasons: 1) the context was closed programmatically by user code; 2) the context was closed during parallel test execution either according to #DirtiesContext semantics or due to automatic eviction from the ContextCache due to a maximum cache size policy.
at org.springframework.util.Assert.state(Assert.java:94) ~[spring-core-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:127) ~[spring-test-5.2.3.RELEASE.jar:5.2.3.RELEASE]
[...]
This makes that the compilation ends in fail, but the execution in the database is recorded as COMPLETED.
Reviewing the code where the error is generated, in the Spring class called DefaultTestContext:
#Override
public ApplicationContext getApplicationContext() {
ApplicationContext context = this.cacheAwareContextLoaderDelegate.loadContext(this.mergedContextConfiguration);
if (context instanceof ConfigurableApplicationContext) {
#SuppressWarnings("resource")
ConfigurableApplicationContext cac = (ConfigurableApplicationContext) context;
Assert.state(cac.isActive(), () ->
"The ApplicationContext loaded for [" + this.mergedContextConfiguration +
"] is not active. This may be due to one of the following reasons: " +
"1) the context was closed programmatically by user code; " +
"2) the context was closed during parallel test execution either " +
"according to #DirtiesContext semantics or due to automatic eviction " +
"from the ContextCache due to a maximum cache size policy.");
}
return context;
}
... the problem is that "context" is not active.
These are my files:
ArqDatasourceConfiguration.java
package com.example.demo;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
#Configuration
public class ArqDatasourceConfiguration {
#Bean
#ConfigurationProperties("spring.batch.datasource")
public DataSource dataSource() throws SQLException {
return DataSourceBuilder.create().build();
}
#Bean
public JdbcTemplate jdbcTemplateBatch(final DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
#Bean(name = "taskDataSource")
#ConfigurationProperties("spring.task.datasource")
public DataSource taskDataSource() throws SQLException {
return DataSourceBuilder.create().build();
}
#Bean
public JdbcTemplate jdbcTemplateTask(#Qualifier("taskDataSource") final DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
CustomTaskConfigurer.java
package com.example.demo;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.task.configuration.DefaultTaskConfigurer;
import org.springframework.stereotype.Component;
#Component
public class CustomTaskConfigurer extends DefaultTaskConfigurer {
#Autowired
public CustomTaskConfigurer(#Qualifier("taskDataSource") DataSource dataSource) {
super(dataSource);
}
}
DemoJobApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.task.configuration.EnableTask;
#SpringBootApplication
#EnableTask
public class DemoJobApplication {
public static void main(String[] args) {
SpringApplication.run(DemoJobApplication.class, args);
}
}
MyJob.java
package com.example.demo;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableBatchProcessing
public class MyJob {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Bean
public Job job2(Step step1, Step step2) {
return jobBuilderFactory.get("job2")
.incrementer(new RunIdIncrementer())
.flow(step1)
.next(step2)
.end()
.build();
}
#Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.tasklet(new MyTasklet("STEP 1"))
.build();
}
#Bean
public Step step2() {
return stepBuilderFactory.get("step2")
.tasklet(new MyTasklet("STEP 2"))
.build();
}
}
MyTasklet.java
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
public class MyTasklet implements Tasklet {
private static final Logger log = LoggerFactory.getLogger(MyTasklet.class);
private String msg;
public MyTasklet(String msg) {
this.msg = msg;
}
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) {
log.info("Executing Tasklet: " + msg);
return RepeatStatus.FINISHED;
}
}
application.properties
spring.batch.initialize-schema=always
spring.main.allow-bean-definition-overriding=true
spring.batch.datasource.jdbc-url=jdbc:postgresql://localhost:5432/postgres
spring.batch.datasource.username=postgres
spring.batch.datasource.password=*****
spring.batch.datasource.driver-class=org.postgresql.Driver
spring.batch.datasource.schema=springbatch
spring.task.datasource.jdbc-url=jdbc:postgresql://localhost:5432/postgres
spring.task.datasource.username=postgres
spring.task.datasource.password=*****
spring.task.datasource.driver-class=org.postgresql.Driver
spring.task.datasource.schema=springtask
DemoJobApplicationTests.java
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
class DemoJobApplicationTests {
#Test
void contextLoads() {
}
}
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.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demoJob</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demoJob</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-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Cloud Task -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-task</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-task-core</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
<!-- ================================== -->
<!-- Database -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- ================================== -->
<!-- Warning #ConfigurationProperties -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- ================================== -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I have tried several annotations like #DirtiesContext, #EnableAutoConfiguration, #SpringBatchTest... but nothing seems to solve the issue, so I would appreciate any idea or help.
Well, after some head banging we have found the solution, ant it is really stu...simply. It is necessary to update the version of the dependencies from Spring Cloud Task in the pom.xml, changing 1.2.2.RELEASE with 2.2.2.RELEASE

Spring WebMVC with Couchbase service - No bean named 'couchbaseRepositoryOperationsMapping' available

I am creating a simple Spring WebMVC app with thymeleaf and now I want to add a service which provides a connection to a couchbase server.
I tried to create the couchbase service on basis of the following tutorial Couchbase with Spring-Boot and Spring Data
I have the following project structure:
src/main/java
com.project
config
MvcWebApplicationInitializer
MvcWebConfig
controller
IndexController
model
Area
Building
BuildingRepository
BuildingService
BuildingServiceImpl
When trying to autowire the service I get the exception that there is no bean named couchbaseRepositoryOperationsMapping which happens because my repository class extends CouchbasePagingAndSortingRepository which throws the exception.
I get the following exception:
[main] INFO org.springframework.web.servlet.DispatcherServlet -
Initializing Servlet 'dispatcher' [main] INFO
org.springframework.data.repository.config.RepositoryConfigurationDelegate
- Multiple Spring Data modules found, entering strict repository configuration mode! [main] INFO
org.springframework.data.repository.config.RepositoryConfigurationDelegate
- Bootstrapping Spring Data repositories in DEFAULT mode. [main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate
- Finished Spring Data repository scanning in 64ms. Found 1 repository interfaces. [main] WARN
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
- Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'buildingServiceImpl': Unsatisfied
dependency expressed through field 'buildingRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'buildingRepository':
'buildingRepository' depends on missing bean
'couchbaseRepositoryOperationsMapping'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'couchbaseRepositoryOperationsMapping' available [main]
ERROR org.springframework.web.servlet.DispatcherServlet - Context
initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'buildingServiceImpl': Unsatisfied
dependency expressed through field 'buildingRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'buildingRepository':
'buildingRepository' depends on missing bean
'couchbaseRepositoryOperationsMapping'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'couchbaseRepositoryOperationsMapping' available
As far as I understand it is not working because there is no bean
named couchbaseRepositoryOperationsMapping.
My MvcWebConfig:
#Configuration
#EnableWebMvc
#ComponentScan("com.xplorg.controller")
#EnableCouchbaseRepositories(basePackages = {"com.xplorg.model"})
public class MvcWebConfig implements WebMvcConfigurer {
#Autowired
private ApplicationContext applicationContext;
#Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
public void configureViewResolvers(ViewResolverRegistry registry) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
registry.viewResolver(viewResolver);
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.project</groupId>
<artifactId>xplorg</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Project</name>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-couchbase</artifactId>
<version>3.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.18.v20190429</version>
</plugin>
</plugins>
</build>
</project>
****Update****
Adding a CouchbaseConfig class fixed the problem with the couchbaseRepositoryOperationsMapping but I get now another error, that there is now named bean buildingRepository. All classes are based on the tutorial Couchbase with Spring-Boot and Spring Data. Do I miss an annotations and therefore spring can not autowire the class?
My repository class:
#N1qlPrimaryIndexed
#ViewIndexed(designDoc = "building")
public interface BuildingRepository extends CouchbasePagingAndSortingRepository<Building, String> {
List<Building> findByCompanyId(String companyId);
Page<Building> findByCompanyIdAndNameLikeOrderByName(String companyId, String name, Pageable pageable);
#Query("#{#n1ql.selectEntity} where #{#n1ql.filter} and companyId = $1 and $2 within #{#n1ql.bucket}")
Building findByCompanyAndAreaId(String companyId, String areaId);
#Query("#{#n1ql.selectEntity} where #{#n1ql.filter} AND ANY phone IN phoneNumbers SATISFIES phone = $1 END")
List<Building> findByPhoneNumber(String telephoneNumber);
#Query("SELECT COUNT(*) AS count FROM #{#n1ql.bucket} WHERE #{#n1ql.filter} and companyId = $1")
Long countBuildings(String companyId);
}
My service class:
#Service
public class BuildingServiceImpl implements BuildingService {
#Autowired
private BuildingRepository buildingRepository;
#Override
public List<Building> findByCompanyId(String companyId) {
return buildingRepository.findByCompanyId(companyId);
}
public List<Building> findByCompanyIdAndNameLike(String companyId, String name, int page) {
return buildingRepository.findByCompanyIdAndNameLikeOrderByName(companyId, name, new PageRequest(page, 20))
.getContent();
}
#Override
public Building findByCompanyAndAreaId(String companyId, String areaId) {
return buildingRepository.findByCompanyAndAreaId(companyId, areaId);
}
#Override
public List<Building> findByPhoneNumber(String telephoneNumber) {
return buildingRepository.findByPhoneNumber(telephoneNumber);
}
#Override
public Building findById(String buildingId) {
return buildingRepository.findById(buildingId).get();
}
#Override
public Building save(Building building) {
return buildingRepository.save(building);
}
#Override
public Long countBuildings(String companyId) {
return buildingRepository.countBuildings(companyId);
}
}
You missed the config class couchebase server
Create a dedicate config class extending the AbstractCouchbaseConfiguration for your couhcebase as below ( server # , user , pwd )
#Configuration
#EnableCouchbaseRepositories(basePackages = {"com.xplorg.model"})
public class CouchbaseConfig extends AbstractCouchbaseConfiguration {
#Override
protected List<String> getBootstrapHosts() {
return Arrays.asList("your server ip (like localhost in local)");
}
#Override
protected String getBucketName() {
return "username";
}
#Override
protected String getBucketPassword() {
return "passsword";
}
}
also change #ComponentScan("com.xplorg.controller") to #ComponentScan("com.xplorg") in your project config so your repositories interface and service should be scanned

Spring Security ACL & OAuth: AclPermissionEvaluator overwritten by DenyAllEvaluator

So I have a SpringBoot application with JavaConfig using spring-security-acl (version 3.2.7.RELEASE) following this tutorial http://krams915.blogspot.com/2011/01/spring-security-3-full-acl-tutorial.html except I'm also using OAuth.
The problem is that the AclPermissionEvaluator is, at runtime, always replaced by DenyAllPermissionEvaluator.
TLDR; how do I get spring-security-acl to work with OAuth2Authentication? each requires #EnableGlobalMethodSecurity but in different locations (acl on the GlobalMethodSecurityConfiguration sub-class, and OAuth2 on the Application). Yet you can't have it defined twice.
Similar to this but with OAuth2: How to configure Spring ACL without XML file )
pom.xml
<project>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<!-- <version>Brixton.M4</version> -->
<version>Angel.SR3</version>
</parent>
<dependencies>
<!-- Spring-boot and cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</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-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
<!-- <version>4.1.0.BUILD-SNAPSHOT</version> -->
<!-- this is intentional to support non-numeric ID's e.g. UUIDs-->
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
<version>${postgres.version}</version>
</dependency>
</dependencies>
</project>
SpringBoot application
#SpringBootApplication
#EnableEurekaClient
#EnableFeignClients(basePackages = "com.mycompany.mypackage.clients")
#EnableOAuth2Resource
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
Java Config
#Configuration
#Slf4j
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class AclSecurityConfig extends GlobalMethodSecurityConfiguration {
#Value("${spring.datasource.url}")
private String jdbcUrl;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
#Value("${spring.datasource.driver-class-name}")
private String driverClass;
#Autowired
private ConversionService defaultConversionService;
#Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
log.info("CreateExpressionHandler() got called");
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
try {
expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(aclService()));
} catch (PropertyVetoException e) {
throw new RuntimeException("Error creating expressionHandler", e);
}
return expressionHandler;
}
#Bean
public MutableAclService aclService() throws PropertyVetoException{
final JdbcMutableAclService mutableAclService = new JdbcMutableAclService(dataSource(), lookupStrategy(), aclCache());
mutableAclService.setClassIdentityQuery("select currval(pg_get_serial_sequence('acl_class', 'id'))");
mutableAclService.setSidIdentityQuery("select currval(pg_get_serial_sequence('acl_sid', 'id'))");
return mutableAclService;
}
public DataSource dataSource() throws PropertyVetoException {
final ComboPooledDataSource cpds = new ComboPooledDataSource(true);
cpds.setJdbcUrl(jdbcUrl);
cpds.setUser(username);
cpds.setPassword(password);
cpds.setDriverClass(driverClass);
return cpds;
}
#Bean
public BasicLookupStrategy lookupStrategy() throws PropertyVetoException {
return new BasicLookupStrategy(dataSource(), aclCache(), aclAuthorizationStrategy(), grantingStrategy(), this.defaultConversionService);
}
#Bean
public AclCache aclCache() {
return new EhCacheBasedAclCache(ehCacheManagerFactoryBean().getObject().getCache("aclCache"), grantingStrategy(), aclAuthorizationStrategy());
}
#Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
cacheManagerFactoryBean.setShared(true);
return cacheManagerFactoryBean;
}
#Bean
public AclAuthorizationStrategy aclAuthorizationStrategy() {
return new AclAuthorizationStrategyImpl(
new SimpleGrantedAuthority("ROLE_ADMIN"),
new SimpleGrantedAuthority("ROLE_ADMIN"),
new SimpleGrantedAuthority("ROLE_ADMIN"));
}
#Bean
public PermissionGrantingStrategy grantingStrategy(){
return new DefaultPermissionGrantingStrategy(auditLogger());
}
#Bean
public AuditLogger auditLogger(){
return new ConsoleAuditLogger();
}
}
Controller
#RepositoryRestController
#ResponseBody
public class SampleRepositoryController {
#Autowired
private MyRepository myRepository;
#PreAuthorize("hasRole('ROLE_USER') and hasPermission(#id, 'com.mycompany.mypackage.services.MyPojo', 'read')")
#RequestMapping(value = "/path/{id}/resource", method = RequestMethod.GET)
public MyObject file(#PathVariable("id") UUID id) {
return myRepository.findOne(id);
}
When I debug/step-thru DefaultMethodSecurityExpressionHandler at runtime I can tell that the permission evaluator is always the DenyAllPermissionEvaluator (and not the AclPermissionEvaluator ) as a new MethodSecurityEvaluationContext gets created.
Note that I do not have nor need the #EnableWebSecurity.
Also, I strongly suspect it's because I have
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true).
defined twice but when I take it off Application.java and run the application (mvn spring-boot:run) it fails to start up with the following error:
2016-02-22 16:04:48.747 INFO 26533 --- [lication.main()] o.apache.catalina.core.StandardService : Stopping service Tomcat
2016-02-22 16:04:48.763 WARN 26533 --- [lication.main()] o.s.boot.SpringApplication : Error handling failed (Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'aclSecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.setApplicationContext(org.springframework.context.ApplicationContext); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cache.config.internalCacheAdvisor' defined in class path resource [org/springframework/cache/annotation/ProxyCachingConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cache.interceptor.BeanFactoryCacheOperationSourceAdvisor]: Factory method 'cacheAdvisor' threw exception; nested exception is java.lang.NullPointerException)
2016-02-22 16:04:48.764 ERROR 26533 --- [lication.main()] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.advaita.cloud.services.samples.Application.main(Application.java:20)
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:497)
at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 23 common frames omitted
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(Assert.java:112)
Does anyone know how to get the 2 to play well together help?

Categories