spring boot(2)-@SpringBootApplication详解

@SpringBootApplication是spring boot最重要的一个注解,用于快捷配置启动类。

启动类

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.java是一个独立的spring boot启动类,这里不应该有业务功能,上一篇的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,并且打印到页面

运行项目

现在的项目结构如下,共三个文件,启动类、配置类、业务类,结构更分明了。

《spring boot(2)-@SpringBootApplication详解》

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

《spring boot(2)-@SpringBootApplication详解》

 

    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/wangb_java/article/details/70943500
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞