java - 基本 Controller 配置在 Spring Boot 中不起作用

标签 java spring spring-mvc spring-boot

我正在使用 Spring Boot 创建一个示例项目,并尝试使用简单的字符串消息映射 / 。为此,我使用了 @Controller 注释。但由于某种原因,映射不起作用。我还包含了 @ComponentScan@EnableWebMvc 但没有运气。

我已经使用maven spring-boot:run 目标来运行。项目上传于https://github.com/tejact/SpringBasicsTreeHouse .

这是 Controller :

package Controller;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Component
@Controller
public class GifController {
    @RequestMapping("/")
    @ResponseBody
    public String listAllGifs() {
        return "Listing all gifs : Madhu";
    }    
}

主要应用入口:

package com.teja;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@EnableAutoConfiguration
@ComponentScan
@EnableWebMvc
public class AppConfig {    
    public static void main(String args[]) {
        SpringApplication.run(AppConfig.class, args);
    }   
}

和 Spring Boot 日志:

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building SpingBasicsTreeHouse 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> spring-boot-maven-plugin:1.4.0.RELEASE:run (default-cli) > test-compile @ SpingBasicsTreeHouse >>>
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ SpingBasicsTreeHouse ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ SpingBasicsTreeHouse ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 2 source files to C:\Users\Teja\git\SpringBasicsTreeHOuse\SpingBasicsTreeHouse\target\classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ SpingBasicsTreeHouse ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ SpingBasicsTreeHouse ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] <<< spring-boot-maven-plugin:1.4.0.RELEASE:run (default-cli) < test-compile @ SpingBasicsTreeHouse <<<
[INFO] 
[INFO] --- spring-boot-maven-plugin:1.4.0.RELEASE:run (default-cli) @ SpingBasicsTreeHouse ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.0.RELEASE)

2016-07-31 13:18:24.593  INFO 11084 --- [           main] com.teja.AppConfig                       : Starting AppConfig on Teja-PC with PID 11084 (C:\Users\Teja\git\SpringBasicsTreeHOuse\SpingBasicsTreeHouse\target\classes started by Teja in C:\Users\Teja\git\SpringBasicsTreeHOuse\SpingBasicsTreeHouse)
2016-07-31 13:18:24.598  INFO 11084 --- [           main] com.teja.AppConfig                       : No active profile set, falling back to default profiles: default
2016-07-31 13:18:24.712  INFO 11084 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@ae4a4a3: startup date [Sun Jul 31 13:18:24 EDT 2016]; root of context hierarchy
2016-07-31 13:18:26.868  INFO 11084 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-07-31 13:18:26.885  INFO 11084 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-07-31 13:18:26.886  INFO 11084 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.4
2016-07-31 13:18:27.002  INFO 11084 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-07-31 13:18:27.003  INFO 11084 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2297 ms
2016-07-31 13:18:27.184  INFO 11084 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2016-07-31 13:18:27.191  INFO 11084 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-07-31 13:18:27.434  INFO 11084 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@ae4a4a3: startup date [Sun Jul 31 13:18:24 EDT 2016]; root of context hierarchy
2016-07-31 13:18:27.582  INFO 11084 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-07-31 13:18:27.587  INFO 11084 --- [           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.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-07-31 13:18:28.004  INFO 11084 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-07-31 13:18:28.082  INFO 11084 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-07-31 13:18:28.087  INFO 11084 --- [           main] com.teja.AppConfig                       : Started AppConfig in 4.278 seconds (JVM running for 12.677)

我的 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>TreeHouse</groupId>
  <artifactId>SpingBasicsTreeHouse</artifactId>
  <version>0.0.1-SNAPSHOT</version>

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

 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.4.0.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

最佳答案

默认@ComponentScan扫描当前包和所有子包。

就您而言AppConfig类在包 com.teja 中和 GifController位于Controller包,因此不会被扫描。

移动GifControllercom.teja.controller例如,或 com.teja 的任何其他子包它会起作用的。

通常我将引导类和所有配置类保留在名为 <com|org|etc>.<myCompany>.<myProject> 的包中然后创建其他包作为该包的子包。

而且你不需要两者 @Component@Controller 。删除@Component -@Controller已经继承@Component

关于java - 基本 Controller 配置在 Spring Boot 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38686566/

相关文章:

java - Spring 3 formBackingObject可以返回不同的命令类吗?

java - ZK Listbox 中的纯 Java 绑定(bind)与 itemRenderer

java - FlowScope 在页面刷新时变得清晰

java - 支持 bean 中的 @ManagedProperty - 设置 getter 和 setter

java - 鉴于参数名称在编译过程中丢失,Spring如何通过参数名称 Autowiring ?

mysql - 如何使用 mvc spring 将 JSON 数组插入 MySQL

java - 如何加载两个ResourceBundle并分别注入(inject)

java - Spring Security - UserRole 或 UserAuthentication

java - 如何使用 JPA 解决 javax.persistence.EntityNotFoundException(不是使用 @NotFound)

java - 按数组选择数据。 sql