SpringBoot解析(一)

本文详细解析SpringBoot启动过程及关键注解的功能,包括@SpringBootApplication、@SpringBootConfiguration与@Bean的作用,通过具体代码示例展示了如何使用这些注解进行配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.SpringBoot启动入口

@SpringBootApplication
@ComponentScan({“com.df”,”da.ser.config”})
public class DfCoreApplication {

public static void main(String[] args) {
    SpringApplication.run(DfCoreApplication.class, args);
}

}

@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 {

@AliasFor(annotation = EnableAutoConfiguration.class, attribute = "exclude")
Class<?>[] exclude() default {};

@AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName")
String[] excludeName() default {};

@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};

@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};

}

前四个注解:是元注解,用来修饰当前注解,就像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,如下:

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,并且打印到页面。

运行项目
现在的项目结构如下,共三个文件
Config.java
Run.java
SampleController.java

通过Run.java的main方法启动项目,访问http://localhost:8080/,
页面输出:Hello World

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值