Spring:连接数据源java安全配置时出错

Spring:连接数据源java安全配置时出错,java,spring,security,spring-mvc,jdbc,Java,Spring,Security,Spring Mvc,Jdbc,我不能在tomcat中破坏我的webapp(基于Spring MVC)。我在试图通过JDBC配置安全性时遇到以下错误: 08-Apr-2016 13:32:22.502 INFO [localhost-startStop-16] org.apache.catalina.core.ApplicationContext.log Spring WebApplicationInitializers detected on classpath: [com.mycompany.web.configurati

我不能在tomcat中破坏我的webapp(基于Spring MVC)。我在试图通过JDBC配置安全性时遇到以下错误:

08-Apr-2016 13:32:22.502 INFO [localhost-startStop-16] org.apache.catalina.core.ApplicationContext.log Spring WebApplicationInitializers detected on classpath: [com.mycompany.web.configuration.JustINFactWebAppInitializer@68223868, com.mycompany.web.configuration.SecurityWebInitializer@255b7004]
08-Apr-2016 13:32:22.735 INFO [localhost-startStop-16] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
08-Apr-2016 13:32:23.490 SEVERE [localhost-startStop-16] org.apache.catalina.core.StandardContext.listenerStart Excepción enviando evento inicializado de contexto a instancia de escuchador de clase org.springframework.web.context.ContextLoaderListener
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource com.mycompany.web.configuration.SecurityConfig.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    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:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    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:4736)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5181)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:945)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1798)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource com.justinfact.web.configuration.SecurityConfig.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 28 more

08-Apr-2016 13:32:23.508 INFO [localhost-startStop-16] org.apache.catalina.core.ApplicationContext.log Closing Spring root WebApplicationContext
我认为我的java配置还可以,但有些地方出了问题。我找不到这个错误。以下是配置文件:

    package com.mycompany.web.configuration;

    import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
WebApplicationInitializer:

public class MycompanyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }
}
证券配置

package com.mycompany.web.configuration;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Gestiona la seguridad de la aplicación a nivel Spring
 * 
 * @author Hadeto Uruguay S.L.
 *
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    @Autowired
    private DataSource dataSource;

    /**
     * Configura el acceso a la aplicación para los usuarios.
     */
    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        String queryUsers = "SELECT bla bla bla bla";
        String queryAuth = "SELECT bla bla bla";
        auth.jdbcAuthentication().dataSource(dataSource).
            usersByUsernameQuery(queryUsers).
            authoritiesByUsernameQuery(queryAuth);
    }

    /**
     * Configuración de la seguridad HTTP.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().
            and().
            formLogin().loginPage("/").permitAll().failureUrl("/").usernameParameter("username").passwordParameter("password").
            and().
            httpBasic().
            and().
            csrf();
    }

}
根配置

package com.mycompany.web.configuration;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan(basePackages={"com.justinfact.web"}, 
               excludeFilters={@Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)})
public class RootConfig {
}

请在
SecurityConfig
类中添加
@配置
@服务
注释

@Configuration
允许类注入Bean,而
@Service
注释使类
SecurityConfig
自动连接到
AutoWired

你可以试试这个。。。我的知识有限,我已根据我面临的相同问题情景向您提出建议


谢谢。

通过配置AppInitializer解决:

package com.mycompany.web.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyCompanytWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        //return new Class<?>[] { RootConfig.class };
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

}
package com.mycompany.web.configuration;
导入org.springframework.web.servlet.support.AbstractAnnotationConfigDispatchersServletInitializer;
公共类MyCompanyTweBapInitializer扩展了AbstractAnnotationConfigDispatchers ServletInitializer{
@凌驾
受保护类[]getRootConfigClasses(){
//返回新类[]{RootConfig.Class};
返回新类[]{WebConfig.Class};
}
@凌驾
受保护的字符串[]getServletMappings(){
返回新字符串[]{”/“};
}
@凌驾
受保护类[]getServletConfigClasses(){
返回null;
}
}

为什么
configure()
方法配置了
@Autowired
属性
@Autowired protected void configure(authenticationmanager builder auth)引发异常
发布完整堆栈跟踪并添加您的
根配置
。您的安全配置已加载(至少应该)由根上下文加载
ContextLoaderListener
这只能从该上下文中而不是从其子上下文中访问bean,即从
DispatcherServlet
访问上下文。包含
DataSource
WebConfig
由后者加载,因此从安全配置的角度来看没有
DataSource
。将定义移动到
RootConfig
,因为它应该放在第一位。Denium您想在哪里更改RootConfig定义的顺序?不需要
@Service
请尝试此
@ComponentScan(basePackages={“com.mycompany.web”,“javax.sql.DataSource”})
请参考此>>您好,我还尝试使用您的解决方案将
WebConfig.class
添加到我的
RootConfigClasses
-数组中,但现在导航到我的应用程序``时没有servlet。您是如何解决上述问题的?是否在配置文件夹中实现了WebConfig.java类?
@Configuration
@Service
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    @Autowired
    private DataSource dataSource;
package com.mycompany.web.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyCompanytWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        //return new Class<?>[] { RootConfig.class };
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

}