我使用start.spring.io初始化了spring boot项目,并添加了WEB,JPA,H2依赖项。
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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.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-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>com.h2database</groupId>
<artifactId>h2</artifactId>
<!-- <scope>runtime</scope> -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
application.properties
spring.h2.console.enabled=true
security.basic.enabled=false
DemoApplication.java
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
UserController.java
@RestController
public class UserController {
@GetMapping("/hello")
public String hello() {
return "Hello";
}
控制台日志
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.10.RELEASE)
2018-02-26 11:24:28.846 INFO 4792 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication on RAJAT-PC with PID 4792 (C:\Users\devra\Downloads\Compressed\demo\target\classes started by rajat in C:\Users\devra\Downloads\Compressed\demo)
2018-02-26 11:24:28.855 INFO 4792 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2018-02-26 11:24:29.018 INFO 4792 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6b67034: startup date [Mon Feb 26 11:24:29 IST 2018]; root of context hierarchy
2018-02-26 11:24:30.894 INFO 4792 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$fa7e8c5a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-02-26 11:24:31.720 INFO 4792 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-02-26 11:24:31.737 INFO 4792 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-02-26 11:24:31.740 INFO 4792 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-02-26 11:24:31.969 INFO 4792 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-02-26 11:24:31.970 INFO 4792 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2957 ms
2018-02-26 11:24:32.307 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-26 11:24:32.308 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-26 11:24:32.309 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-26 11:24:32.309 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-26 11:24:32.310 INFO 4792 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-02-26 11:24:32.311 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-02-26 11:24:32.313 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'webServlet' to [/h2-console/*]
2018-02-26 11:24:33.004 INFO 4792 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-02-26 11:24:33.038 INFO 4792 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-02-26 11:24:33.196 INFO 4792 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2018-02-26 11:24:33.199 INFO 4792 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-02-26 11:24:33.202 INFO 4792 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2018-02-26 11:24:33.266 INFO 4792 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-02-26 11:24:33.517 INFO 4792 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2018-02-26 11:24:33.807 INFO 4792 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2018-02-26 11:24:33.816 INFO 4792 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2018-02-26 11:24:33.859 INFO 4792 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-02-26 11:24:34.365 INFO 4792 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6b67034: startup date [Mon Feb 26 11:24:29 IST 2018]; root of context hierarchy
2018-02-26 11:24:34.506 INFO 4792 --- [ 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)
2018-02-26 11:24:34.508 INFO 4792 --- [ 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)
2018-02-26 11:24:34.568 INFO 4792 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:34.569 INFO 4792 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:34.663 INFO 4792 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:35.147 INFO 4792 --- [ main] b.a.s.AuthenticationManagerConfiguration :
Using default security password: dd5212d7-4de1-4fee-9f6b-f5cd888f2f17
2018-02-26 11:24:35.222 INFO 4792 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2018-02-26 11:24:35.334 INFO 4792 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$ApplicationNoWebSecurityConfigurerAdapter$1@11c713b7, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@2251b3bc, org.springframework.security.web.context.SecurityContextPersistenceFilter@602f8f94, org.springframework.security.web.header.HeaderWriterFilter@2785db06, org.springframework.security.web.csrf.CsrfFilter@603cabc4, org.springframework.security.web.authentication.logout.LogoutFilter@7a9ceddf, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4dfe8b37, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@7e64c1a9, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3fbe503c, org.springframework.security.web.session.SessionManagementFilter@715a70e9, org.springframework.security.web.access.ExceptionTranslationFilter@1cc8416a]
2018-02-26 11:24:35.552 INFO 4792 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-02-26 11:24:35.652 INFO 4792 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-02-26 11:24:35.670 INFO 4792 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 7.302 seconds (JVM running for 7.824)
你可以看到spring没有映射
/hello
url
答案 0 :(得分:3)
Spring参考文档说 - 通常建议您将主应用程序类放在其他类(如
)之上的根包中
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
有关更多信息,请参阅此链接:
https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html
答案 1 :(得分:3)
考虑到其他答案并不能解释为什么它没有按预期工作,这就是原因。
Spring使用组件扫描来查找符合条件的bean(@Repository
,@Service
,@Component
,@Controller
,...)。这通常通过使用@ComponentScan
注释来完成。
这在core docs:
要自动检测这些类并注册相应的bean,您需要将
@ComponentScan
添加到@Configuration
类,其中basePackages
属性是这两个类的公共父包。 (或者,您可以指定包含每个类的父包的逗号/分号/空格分隔列表。)
Spring Boot默认只扫描主类的同一个包(包括子包)中的组件。这是因为@SpringBootApplication
注释默认包含@ComponentScan
,如Spring boot docs中所述:
@SpringBootApplication
注释相当于使用@Configuration
,@EnableAutoConfiguration
和@ComponentScan
及其默认属性
如果您希望Spring自动检测您的控制器,您有三种选择:
将控制器移至com.example.demo
包。这是根据Spring boot documentation建议的方法。
通过添加controller
注释来告诉Spring查看@ComponentScan
包:
@SpringBootApplication
@ComponentScan({"com.example.demo", "controller"}) // Add this
public class DemoApplication {
// ...
}
通过配置controller
的{{1}}属性来告诉Spring查看scanBasePackages
包:
@SpringBootApplication