spring boot(2)-@SpringBootApplication详解

pom.xml

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

Run.java
package hello;

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;

@SpringBootApplication
public class Run{
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Run.class, args);
    }
}
这个Run是一个单独的项目启动类,这里不应该有业务功能,上一篇的hello world业务代码应该写在一个单独的@Controller里面,和上一篇相比,这里用@SpringBootApplication替换了@EnableAutoConfiguration。

@SpringBootApplication
@EnableAutoConfiguration:只是实现自动配置一个功能,具体参考上一篇
@SpringBootApplication:是一个组合注解,包括@EnableAutoConfiguration及其他多个注解,是一个项目的启动注解
在eclipse的代码中 按 crtl+左键 点击@SpringBootApplication注解可以查看他的源码,如下
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
		@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication
前四个注解:是元注解,用来修饰当前注解,就像public类的修饰词,没有实际功能,如果不打算写自定义注解,不需要了解
后三个注解:是真正起作用的注解,包括
@SpringBootConfiguration:当前类是一个配置类,就像xml配置文件,而现在是用java配置文件,效果是一样的
@EnableAutoConfiguration:上篇已经讲了
@ComponentScan:用注解配置实现自动扫描,默认会扫描当前包和所有子包,和xml配置自动扫描效果一样,@Filter是排除了两个系统类

@SpringBootConfiguration和@Bean

package hello;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

@SpringBootConfiguration
public class Config {
	@Bean
	public String hello(){
		return "Hello World";
	}
}

@SpringBootConfiguration:说明这是一个配置文件类,它会被@ComponentScan扫描到

@Bean:就是在spring容器中声明了一个bean,赋值为hello world,String方法类型就是bean的类型,hello方法名是bean的id

如果是用xml配置文件来声明bean,如下图

<bean id="hello" class="String"></bean>


SampleController.java

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
public class SampleController {
	@Autowired
	String hello;
	
	@RequestMapping(value="/")
	@ResponseBody
    String test(){
      return hello;
    }

   
}

把hello world业务功能独立出来,在这里注入了spring容器中的那个String类型的Bean,并且打印到页面


运行项目

现在的项目结构如下,共三个文件


通过Run.java的main方法启动项目,访问http://localhost:8080/

 

posted @ 2017-04-29 08:05  free_java  阅读(426)  评论(0编辑  收藏  举报