@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);
}
}
@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
@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/
634



被折叠的 条评论
为什么被折叠?



