简体   繁体   English

休息控制器没有映射在Spring Boot

[英]Rest controller not mapping in spring boot

My application runs but nothing about mapping is shown in console. 我的应用程序正在运行,但控制台中未显示任何有关映射的信息。 My Application class file is above controller and also added @ComponentScan(basePackages : "com.org.name.controller") to scan for controllers. 我的Application类文件位于控制器之上,并且还添加了@ComponentScan(basePackages:“ com.org.name.controller”)来扫描控制器。 Still no mapping shows up in console. 控制台中仍未显示任何映射。 I have commented out @Autowired in controller class as i was getting error of : 我在控制器类中已注释掉@Autowired,因为我遇到以下错误:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-07-12 11:05:16.014 ERROR 14104 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field userService in com.homzhub.lms.controller.UserController required a bean of type 'com.homzhub.lms.service.UserService' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.homzhub.lms.service.UserService' in your configuration.

Main class: 主班:

package com.homzhub.lms;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = {"com.homzhub.lms.controller"})
//@EnableJpaRepositories("repository")
//@EnableAutoConfiguration
public class LmsApplication{
    public static void main(String[] args){
        SpringApplication.run(LmsApplication.class, args);
    }
}

appointment controller : 预约控制器:

package com.homzhub.lms.controller;

import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.homzhub.lms.entity.Appointment;
import com.homzhub.lms.entity.User;
import com.homzhub.lms.service.AppointmentService;
import com.homzhub.lms.service.UserService;



@Controller
@RequestMapping(path = "/appointment")
public class AppointmentController {

   // @Autowired
    private AppointmentService appointmentService;

    //@Autowired
    private UserService userService;

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public void createAppointment(Model model) {
        Appointment appointment = new Appointment();
        model.addAttribute("appointment", appointment);
        model.addAttribute("dateString", "");
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createAppointmentPost(@ModelAttribute("appointment") Appointment appointment, @ModelAttribute("dateString") String date, Model model, Principal principal) throws ParseException {

        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        Date d1 = format1.parse(date);
        appointment.setDate(d1);

        User user = userService.findByUsername(principal.getName());
        appointment.setUser(user);

        appointmentService.createAppointment(appointment);

        return "redirect:/userFront";
    }
}

pom.xml file : 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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
<!--        <version>1.5.21.RELEASE</version>  -->
        <version>2.1.6.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.homzhub</groupId>
    <artifactId>lms</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>lms</name>
    <description>Lead Management System</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</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.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            </dependency>
    </dependencies>

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

</project>

Console output. 控制台输出。 After commenting out @Autowired in controller classes the application runs but no mapping is done : 在控制器类中注释掉@Autowired之后,该应用程序将运行,但不执行任何映射:

2019-07-12 12:58:04.638  INFO 18828 --- [           main] com.homzhub.lms.LmsApplication           : Starting LmsApplication v0.0.1-SNAPSHOT on rms-Lenovo-ideapad-330-15IKB with PID 18828 (/home/rms/lms/target/lms-0.0.1-SNAPSHOT.jar started by rms in /home/rms/lms)
2019-07-12 12:58:04.644  INFO 18828 --- [           main] com.homzhub.lms.LmsApplication           : No active profile set, falling back to default profiles: default
2019-07-12 12:58:05.941  INFO 18828 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-12 12:58:06.161  INFO 18828 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 204ms. Found 13 repository interfaces.
2019-07-12 12:58:06.849  INFO 18828 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d931452d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-07-12 12:58:07.301  INFO 18828 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-12 12:58:07.350  INFO 18828 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-12 12:58:07.350  INFO 18828 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-12 12:58:07.484  INFO 18828 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-12 12:58:07.484  INFO 18828 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2751 ms
2019-07-12 12:58:07.952  INFO 18828 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-07-12 12:58:08.286  INFO 18828 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-07-12 12:58:08.388  INFO 18828 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-07-12 12:58:08.519  INFO 18828 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.10.Final}
2019-07-12 12:58:08.521  INFO 18828 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-07-12 12:58:08.773  INFO 18828 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-07-12 12:58:09.175  INFO 18828 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-07-12 12:58:10.967  INFO 18828 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-07-12 12:58:12.284  INFO 18828 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-12 12:58:12.364  WARN 18828 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-07-12 12:58:12.923  INFO 18828 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
2019-07-12 12:58:13.211  INFO 18828 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: f1e93a8f-d01a-4050-8724-87ff348fab02

2019-07-12 12:58:13.388  INFO 18828 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@1dcca8d3, org.springframework.security.web.context.SecurityContextPersistenceFilter@6daf2337, org.springframework.security.web.header.HeaderWriterFilter@70e3f36f, org.springframework.security.web.csrf.CsrfFilter@3c7cfcbb, org.springframework.security.web.authentication.logout.LogoutFilter@7d755813, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@4e25147a, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@60e5272, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@5631962, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@56303475, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@250b236d, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@432034a, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@52a70627, org.springframework.security.web.session.SessionManagementFilter@23e44287, org.springframework.security.web.access.ExceptionTranslationFilter@1bfe3203, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@71870da7]
2019-07-12 12:58:13.517  INFO 18828 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-12 12:58:13.520  INFO 18828 --- [           main] com.homzhub.lms.LmsApplication           : Started LmsApplication in 9.518 seconds (JVM running for 10.158)

UserService class : UserService类别:

package com.homzhub.lms.service;

import java.util.List;
import java.util.Set;
import org.springframework.stereotype.Service;
import com.homzhub.lms.entity.User;
import com.homzhub.lms.security.UserRole;
//@Service("userDetailsService")
@Service
public interface UserService{
    User findByUsername(String username);
    User findByEmail(String email);
 //   User findByPhoneNumber(String phoneNumber);
    boolean checkUserExists(String username, String email);
    boolean checkUsernameExists(String username);
    boolean checkEmailExists(String email);
    void save(User user);
    User createUser(User user, Set<UserRole> userRoles);
    User saveUser(User user);
    List<User> findUserList();
    void enableUser(String username);
    void disableUser(String username);
}

If it isn't already, you need to define UserService as a Component, or more appropriately as a Service. 如果尚未定义,则需要将UserService定义为Component,或更恰当地定义为Service。 If it already is you have to map it, which is a bit weird considering Spring should do that on its own. 如果已经存在,则必须对其进行映射,考虑到Spring应该自己进行映射,这有点奇怪。

Your are only scanning com.homzhub.lms.controller and UserService is not under ComponentScan. 您仅在扫描com.homzhub.lms.controllerUserService不在ComponentScan下。 You need to add service package to ComponentScan 您需要将服务包添加到ComponentScan

@ComponentScan(basePackages = {"com.homzhub.lms"})

You service is under com.homzhub.lms.service package so you have to add this package to @ComponentScan too, so Spring will scan this package too and pick up the classes marked with stereotypes there : 您的服务位于com.homzhub.lms.service包下,因此您也必须将此包也添加到@ComponentScan ,因此Spring也会扫描此包并在其中拾取带有构造型的类:

@SpringBootApplication
@ComponentScan(basePackages = {"com.homzhub.lms.controller, "com.homzhub.lms.service"})
public class LmsApplication{
    public static void main(String[] args){
        SpringApplication.run(LmsApplication.class, args);
    }
}

However I can see that your class annotated with @SpringBootApplication is already above all the packages with your components so you could get rid of @ComponentScan annotation at all. 但是我可以看到,使用@SpringBootApplication注释的类已经位于所有包含组件的软件包之上,因此您可以完全摆脱@ComponentScan注释。 So it will scan nested packages by default. 因此,默认情况下它将扫描嵌套的程序包。

And also remember about annotating your service classes with Spring stereotypes annotations for example @Service so component scan will be able to pick them up. 还要记住有关使用Spring @Service型注释(例如@Service注释服务类的信息,以便组件扫描能够识别它们。

Uncomment @Autowired annotation. 取消注释@Autowired注释。 Put @Service annotation on the implementing class instead of the interface and make sure your implementing class is discover-able via componentScan . @Service批注放在实现类而不是接口上,并确保可以通过componentScan发现实现类。

Also, as a side note, Spring will scan all subpackages of your main class (class with @SpringBootApplication annotation). 另外,作为附带说明,Spring将扫描您的主类(带有@SpringBootApplication批注的类)的所有子包。 So it would be a good idea to have a directory structure like com.homzhub.lms as a root and com.homzhub.lms.controller for controllers com.homzhub.lms.service for service and com.homzhub.lms.service.impl if you want to keep implementations in a different package. 因此,最好有一个目录结构,如com.homzhub.lms作为根目录, com.homzhub.lms.controller用于控制器com.homzhub.lms.service用于服务, com.homzhub.lms.service.impl如果要将实现保留在其他程序包中。

If you are following this structure, you won't need componentScan . 如果遵循此结构,则不需要componentScan

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

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