简体   繁体   English

无法在 Spring Boot 项目中自动装配数据源

[英]Cannot Autowire DataSource in Spring Boot Project

I am trying to build a simple Spring Boot CRUD application that also has login and signup options with spring boot security.我正在尝试构建一个简单的 Spring Boot CRUD 应用程序,该应用程序还具有登录和注册选项以及 Spring Boot 安全性。 I'm already working with a MySQL database and its working fine to persist the data for my application.我已经在使用 MySQL 数据库,它可以很好地为我的应用程序保留数据。

The problem is that, in trying to create my jdbcAuthentication, in my securityConfig class, it says that I cannot autowire Datasource, and that there are no beans of 'DataSource' type found (again, I have used my MySQL database successfully for this project, for a while now).问题是,在尝试创建我的 jdbcAuthentication 时,在我的 securityConfig 类中,它说我无法自动装配数据源,并且没有找到“数据源”类型的 bean(同样,我已经成功地为这个项目使用了我的 MySQL 数据库, 有一段时间了)。 It also automatically imports the javax.sql.DataSource import when I type it in, so it does recognize it.当我输入它时,它还会自动导入 javax.sql.DataSource 导入,因此它确实可以识别它。

I tried to search through similar questions, but just could not get it to work.我试图搜索类似的问题,但无法让它发挥作用。

Here is my code:这是我的代码:

Test2Application.java Test2Application.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Test2Application {

public static void main(String[] args) {
    SpringApplication.run(Test2Application.class, args);
}
}

SecurityConfig.java安全配置.java

package com.example.demo;

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;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.sql.DataSource;

@EnableWebSecurity
@RequestMapping("cheese")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select email as principal, password as credentials, true from user where email=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .authorizeRequests()
                .antMatchers(
                        "/cheese/index",
                        "/cheese/",
                        "/**/webjars/**",
                        "/cheese/signup",
                        "/cheese/login",
                        "/cheese/account",
                        "/cheese/add",
                        "/cheese/remove",
                        "/cheese/success").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/cheese/login")
                .permitAll();

       http.csrf().disable();
    }
}

UserController.java用户控制器.java

package com.example.demo.controllers;

import com.example.demo.models.Customer;
import com.example.demo.models.data.CustomerDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("cheese")
public class UserController {

    @Autowired
    private CustomerDao customerDao;

    @RequestMapping(value = "login")
    public String loginPage(Model model) {
        model.addAttribute("title", "Login Page");
        return "cheese/login";
    }

    @RequestMapping(value = "account")
    public String accountInfo(Model model) {
        model.addAttribute("title", "Account Page");
        return "cheese/account";
    }

    @GetMapping("signup")
    public String displaySignUpForm(Model model) {
        model.addAttribute("title", "Sign Up");
        model.addAttribute("customer", new Customer());
        return "cheese/signup";
    }

    @PostMapping(value = "signup")
    public String processSignUp(Model model, @ModelAttribute Customer customer, Errors errors) {

        if (errors.hasErrors()) {
            return "cheese/signup";
        }

        customerDao.save(customer);
        return "cheese/success";
    }
}

Application.Properties应用程序属性

spring.datasource.url=jdbc:mysql://localhost:8889/******?useSSL=false
spring.datasource.username=****
spring.datasource.password=******

spring.jpa.database=MYSQL

spring.jpa.hibernate.ddl-auto = update

spring.jpa.show-sql=false

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Pom.xml 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>com.example</groupId>
    <artifactId>test2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>test2</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</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-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The Spring Security configuration should applied with the Configuration annotation. Spring Security配置应与Configuration批注一起应用。 Remove @RequestMapping("cheese") from SecurityConfig SecurityConfig删除@RequestMapping("cheese")

The correct configuration: 正确的配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter 

Had the same issue, I created a separate config class where I defined a DataSource bean有同样的问题,我创建了一个单独的配置类,在其中定义了一个 DataSource bean

@Bean
    DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl("database_url");
        dataSource.setUsername("username");
        dataSource.setPassword("password");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return dataSource;
    }

and in the main config file (in your case Security config) left DataSource @Autowired.并在主配置文件(在您的情况下为安全配置)中留下 DataSource @Autowired。

@Autowired
    DataSource dataSource;

    @Autowired
    protected void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource);
    }

And it worked.它奏效了。 In case it is useful, I used these Gradle dependencies -如果有用,我使用了这些 Gradle 依赖项 -

implementation 'mysql:mysql-connector-java:8.0.18'
implementation group: 'org.springframework', name: 'spring-jdbc', version: '5.3.21'

Apart from the @Configuration annotation, add @EnableAutoConfiguration which would attempt and configure code. 除了@Configuration批注之外,添加@EnableAutoConfiguration ,它将尝试并配置代码。

    @Configuration
    @EnableAutoConfiguration
    public class SecurityConfig extends WebSecurityConfigurerAdapter 

Also, rebuild your sources afterwards. 另外,之后再重建源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM