Spring Security ACL & OAuth: AclPermissionEvaluator overwritten by DenyAllEvaluator - java

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?

Related

#JedisConnectionFactory java.lang.NoSuchMethodError: org.springframework.util.Assert.isTrue(ZLjava/util/function/Supplier;)V

My pom is:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.3</version>
</dependency>
And my config redis:
private static final String redisHost = LocalProperties.getInstance().getString("spring.redis.host");
private static final int redisPort = LocalProperties.getInstance().getInteger("spring.redis.port");
#Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConFactory = new JedisConnectionFactory();
jedisConFactory.setHostName(redisHost);
jedisConFactory.setPort(redisPort);
return jedisConFactory;
}
#Bean
public RedisTemplate<String, String> redisTemplate() {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
When i deploy it on jboss EAP massagement then throw exception:
java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jedisConnectionFactory' defined in com.phillip.poemsglobal.st.config.RedisConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.jedis.JedisConnectionFactory]: Factory method 'jedisConnectionFactory' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.util.Assert.isTrue(ZLjava/util/function/Supplier;)V
I check the reason is conflict version of spring-data-redis with jedis. But I checked here (https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis/2.1.8.RELEASE) that identify that my config is correct. So I have been not understood. Please help me!!!

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 Boot 2 Upgrade with JPA Failed to instantiate [com.zaxxer.hikari.HikariDataSource]

I'm upgrading to Spring Boot 2.0.1.RELEASE, using Spring data JPA with Eclipselink as my provider and Liquibase. I'm encountering the following error trying to start the server:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [com/zoomdata/scheduler/service/dao/JPASpringConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Illegal arguments to factory method 'dataSource'; args: ; nested exception is java.lang.IllegalArgumentException: wrong number of arguments
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1702)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:579)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:859)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:137)
at com.zoomdata.scheduler.service.Main.main(Main.java:54)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Illegal arguments to factory method 'dataSource'; args: ; nested exception is java.lang.IllegalArgumentException: wrong number of arguments
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$1(AbstractBeanFactory.java:353)
at org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:385)
at org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:184)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:350)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
at com.zaxxer.hikari.HikariDataSource$$EnhancerBySpringCGLIB$$fea845fa.getConnection(<generated>)
at com.zoomdata.scheduler.service.dao.JPASpringConfiguration$1.afterPropertiesSet(JPASpringConfiguration.java:85)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1761)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1698)
... 17 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Illegal arguments to factory method 'dataSource'; args: ; nested exception is java.lang.IllegalArgumentException: wrong number of arguments
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:172)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
... 32 common frames omitted
Caused by: java.lang.IllegalArgumentException: wrong number of arguments
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.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 33 common frames omitted
The dependencies in my POM are:
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
<version>2.0.0.RC1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.0.1.RELEASE</version>
<exclusions>
<exclusion>
<artifactId>hibernate-core</artifactId>
<groupId>org.hibernate</groupId>
</exclusion>
<exclusion>
<artifactId>hibernate-entitymanager</artifactId>
<groupId>org.hibernate</groupId>
</exclusion>
<exclusion>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.0.7.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.2</version>
</dependency>
</dependencies>
My JPA Configuration class looks like:
#Configuration
#EnableJpaRepositories("com.example.my.classes")
#EntityScan({"com.example.entities"})
public class JPASpringConfiguration extends JpaBaseConfiguration {
private String targetDatabase;
private final String sqlLoggingLevel;
#Autowired
public JPASpringConfiguration(
#Value("${spring.datasource.target-database}") String targetDatabase,
#Value("${eclipselink.logging.level.sql:INFO}") String sqlLoggingLevel,
DataSource dataSource,
JpaProperties jpaProperties,
ObjectProvider<JtaTransactionManager> transactionManagerObjectProvider,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
super(dataSource, jpaProperties, transactionManagerObjectProvider, transactionManagerCustomizers);
this.targetDatabase = targetDatabase;
this.sqlLoggingLevel = sqlLoggingLevel;
}
#Override
protected AbstractJpaVendorAdapter createJpaVendorAdapter() {
return new EclipseLinkJpaVendorAdapter();
}
#Override
protected Map<String, Object> getVendorProperties() {
HashMap<String, Object> map = new HashMap<>();
map.put("eclipselink.weaving", "false");
map.put("eclipselink.target-database", targetDatabase);
map.put("eclipselink.logging.level.sql", sqlLoggingLevel);
map.put("eclipselink.cache.shared.default", "false");
map.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, IDSequenceRegistrar.class.getName());
return map;
}
#Bean
public SpringLiquibase liquibase(DataSource dataSource) {
SpringLiquibase springLiquibase = new SpringLiquibase() {
#Override
public void afterPropertiesSet() throws LiquibaseException {
configureLiquibase();
Liquibase liquibase = null;
try (Connection versionConnection = dataSource.getConnection()) {
versionConnection.setAutoCommit(true);
liquibase = createLiquibase(dataSource.getConnection());
String version = getDbVersion(versionConnection);
String previous = null;
while (!Objects.equals(version, previous)) {
setContexts(version);
performUpdate(liquibase);
previous = version;
version = getDbVersion(versionConnection);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (liquibase != null && liquibase.getDatabase() != null) {
liquibase.getDatabase().close();
}
}
}
};
springLiquibase.setDataSource(dataSource);
springLiquibase.setChangeLog("classpath:/upgrade/db-changelog.xml");
return springLiquibase;
}
private String getDbVersion(Connection connection) throws SQLException {
String sql = "select tag from databasechangelog where tag is not null order by dateexecuted desc";
try (Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql)) {
if (rs.next()) {
return rs.getString(1);
}
return "initial";
} catch (SQLException e) {
try (ResultSet rs = connection.getMetaData().getTables(null, null, "databasechangelog", null)) {
if (rs.next()) {
throw e;
} else {
return "initial";
}
}
}
}
private void configureLiquibase() {
ChangeFactory.getInstance().register(ChangeSetAwareCustomChangeWrapper.class);
}
}
In my application.properties, I have defined:
spring.datasource.target-database=PostgreSQL
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/mydatabase
spring.datasource.username=myuser
spring.datasource.password=mypassword
spring.datasource.max-active=20
spring.datasource.max-idle=4
spring.datasource.max-wait=60000
spring.datasource.min-idle=2
spring.datasource.test-on-borrow=true
spring.datasource.test-on-return=true
spring.datasource.time-between-eviction-runs-millis=120000
spring.datasource.validation-query=select 1
This worked previously in Spring Boot 1.3.5 (before the HikariCP switch in Spring Boot 2). JPASpringConfiguration was formerly able to invoke super() without the additional arguments.
When I put a breakpoint in SimpleInstantiationStrategy, I can see the args passed are null.
So far I've tried:
Using spring.datasource.hikari.* properties
Adding #AutoConfigureAfter({ DataSourceAutoConfiguration.class }) to my
configuration class
Upgrading HikariCP to 3.2.0 from what's currently provided by Spring Boot
Several other reworkings of various config options, properties, and classes
Thank you to anyone who can help!
I am able to use springboot with hikari. I do not see following class. Can you add and check?
#Configuration
#ConfigurationProperties(prefix = "spring.datasource.hikari")
public class CustomHikariConfig extends HikariConfig {
#Bean
public DataSource dataSource() {
return new HikariDataSource(this);
}
}
Though you already mentioned that you have used spring.datasource.hikari.*, you can recheck one more time with below mentioned properties(In case if you have missed any)
###
# HikariCP Properties
###
spring.datasource.hikari.connection-timeout=60000
spring.datasource.hikari.maximum-pool-size=200
spring.datasource.hikari.minimum-idle=30
spring.datasource.hikari.idle-timeout=3000
spring.datasource.hikari.poolName=HikariCP
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.jdbcUrl=**data source url**
spring.datasource.hikari.username=**username**
spring.datasource.hikari.password=**password**
spring.datasource.hikari.driverClassName=com.mysql.jdbc.Driver
mycase is problem in pom.xml
i use oracle and i add this one. it works
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.oracle.database.nls</groupId>
<artifactId>orai18n</artifactId>
</dependency>

Spring Boot 2.0.0 cycle bean dependency EntityManger and SessionFactory

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

No qualifying bean of type [org.springframework.security.config.annotation.web.builders.HttpSecurity] found for dependency

I'm trying create java web application with Spring Security + Spring MVC. I go error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: protected void ggdb.SecurityConfiguration.configure(org.springframework.security.config.annotation.web.builders.HttpSecurity) throws java.lang.Exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.web.builders.HttpSecurity] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4937)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: protected void ggdb.SecurityConfiguration.configure(org.springframework.security.config.annotation.web.builders.HttpSecurity) throws java.lang.Exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.web.builders.HttpSecurity] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.web.builders.HttpSecurity] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:600)
... 24 more
My pom.xml:
<properties>
<spring.version>4.1.2.RELEASE</spring.version>
<spring.security.version>3.2.5.RELEASE</spring.security.version>
<javax.servlet.version>3.1.0</javax.servlet.version>
<mysql.connector.version>5.1.34</mysql.connector.version>
<hibernate.version>4.3.7.Final</hibernate.version>
<commons.dbcp2.version>2.0.1</commons.dbcp2.version>
<jstl.version>1.2</jstl.version>
</properties>
<build>
<filters>
<filter>filters/maven.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons.dbcp2.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
My Initializer:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
My RootConfiguration:
#Configuration
#ComponentScan
public class RootConfiguration {
}
and SecuriryConfiguration:
#Configuration
#EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Autowired
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.permitAll();
}
public UserDetailsService getUserDetailsService() {
return userDetailsService;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
}
Could you tell me what is source of problem?
Try removing the #Autowired annotation of the configure(HttpSecurity http) method. The WebSecurityConfigurerAdapter should provide you with the HttpSecurity automatically.

Categories