当前位置: 首页 > 知识库问答 >
问题:

使用mysql保护spring启动-未找到EntityRangerFactory

闻人树
2023-03-14

我尝试使用安全性和mysql作为提供者来保护我的spring boot应用程序。

调试应用程序时,出现以下错误:

SysUserService中的字段sysUserRepository需要一个名为entityManagerFactory的bean,但找不到。

我已经看过这个问题了

如何使用Spring Boot与MySQL数据库和JPA?

这是SysUserService

package com.cm.sb.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cm.sb.model.SysUser;
import com.cm.sb.repository.SysUserRepository;

@Service
public class SysUserService {

    @Autowired
    SysUserRepository sysUserRepository;

    public SysUser findByusername(String username) {
        return sysUserRepository.findByUsername(username);
    }

}

这是我的Spring启动初始化器

package com.cm.sb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication(scanBasePackages={"com.cm.sb"},exclude = { SecurityAutoConfiguration.class })
@EnableJpaRepositories(basePackages = "com.cm.sb")
public class SbApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SbApplication.class);
    }


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

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/sb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=none

spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

security.user.password=ciro
security.user.username=ciro 

这是我的安全配置类

package com.cm.sb.config;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userDetailService")
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("**/login"))
        .and().authorizeRequests().antMatchers("/dashboard").hasRole("USER")
        .and().authorizeRequests().antMatchers("/home").permitAll()
        .and().formLogin().defaultSuccessUrl("/dashboard").loginPage("/login")
        .and().logout().permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/*.css");
        web.ignoring().antMatchers("/*.js");
    }
}   

这是我的存储库类

package com.cm.sb.repository;

import com.cm.sb.model.SysUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository("sysUserRepository")
public interface SysUserRepository extends JpaRepository<SysUser, Integer> {

    SysUser findByUsername(String username);
}

编辑:我的pom

<?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.cm</groupId>
    <artifactId>sb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.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>
        <hibernate.version>4.3.11.Final</hibernate.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-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- necessaria per le jsp -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

共有1个答案

郎曜文
2023-03-14

我尝试使用与您之前发布的代码相同的代码,我可以启动服务启动。

这是我改变的一切:

package com.cm.sb.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.cm.sb.entity.SysUser;

    public interface SysUserRepository extends JpaRepository<SysUser, Integer> {

        SysUser findByUsername(String username);
    }

主要类:

package com.cm.sb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
@EnableJpaRepositories(basePackages = "com.cm.sb.repository")
@ComponentScan("com.cm.sb.service")
@EntityScan("com.cm.sb.entity")
public class SbExampleApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SbExampleApplication.class);
    }

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

属性文件:

spring.datasource.url=jdbc:mysql://localhost:3306/sb
spring.datasource.username=root
spring.datasource.password=
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create // because i want to generate the db from entities

spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

security.user.password=ciro
security.user.username=ciro 

堆栈跟踪:

2018-11-29 18:19:17.746  INFO 6340 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-11-29 18:19:17.802  INFO 6340 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-29 18:19:17.802  INFO 6340 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-29 18:19:17.862  INFO 6340 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-29 18:19:18.161  INFO 6340 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-11-29 18:19:18.163  INFO 6340 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-11-29 18:19:18.171  INFO 6340 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-11-29 18:19:18.257  INFO 6340 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-29 18:19:18.260  INFO 6340 --- [           main] com.cm.sb.SbExampleApplication           : Started SbExampleApplication in 5.051 seconds (JVM running for 5.991)
 类似资料:
  • 我正在使用KeyClope来保护我的Spring Boot rest应用程序。 该应用程序还具有React前端。 我的问题是-前端是否也应该使用KeyClope进行保护? 如果没有,您将在何时保护前端和后端?

  • 启用触摸保护 把 Yubikey-manager 安装在一个绝对路径:【译者注:homebrew 是 macOS 平台的包管理软件】 ❯ brew install libu2f-host libusb swig ykpers ❯ git clone git@github.com:Yubico/Yubikey-manager.git ❯ git submodule update --init --r

  • 在我的Spring Boot应用程序中,我从Thymeleaf切换到JSP,它在我的本地计算机上正常工作,但当我将它上传到Heroku服务器时,我发现出现了一个意外错误(type=notfound,status=404)/WEB-INF/jsp/home。jsp 它的罐子打包,如果它在本地工作,但不是在Heroku服务器上,这意味着什么?

  • 我正在尝试从S3导入一个JSON数据,在进行一些查询后,将输出作为JSON格式再次导出到S3。但是,我在EMR集群上的配置单元步骤中得到“org.apache.hadoop.hive.serde2.serdeException:java.io.ioException:Start token not found where expected”错误。为了理解问题是什么,我简化了Hive脚本和JSON数

  • 有没有办法只使用spring security实现CSRF保护,而不使用身份验证和授权等其他功能? 我尝试了以下配置,但它关闭了spring security的所有功能。想知道是否有一种方法可以配置csrf功能。