简述 SpringBoot的核心注解 以及常用注解 ?
参考答案:
Spring Boot 的核心注解是 @SpringBootApplication
,这个注解通常被用在 Spring Boot 的主类上,用于标识这是一个 Spring Boot 应用,并开启 Spring Boot 的各项能力。这个注解实际上是 @SpringBootConfiguration
、@EnableAutoConfiguration
和 @ComponentScan
这三个注解的组合。
@SpringBootConfiguration
:这个注解表示该类是一个 Spring Boot 配置类,它告诉 Spring Boot 开始加载配置信息。这个注解实际上是一个特殊的@Configuration
,表示该类是一个配置类,用于定义 Spring 的 Java 配置。@EnableAutoConfiguration
:这个注解告诉 Spring Boot 根据你添加的 jar 依赖自动配置你的 Spring 应用。例如,如果你的 classpath 下有spring-boot-starter-web
,Spring Boot 会自动配置所有与 web 相关的默认设置。@ComponentScan
:这个注解让 Spring Boot 扫描到Configuration
类并把它加入到程序上下文。默认会扫描启动类所在包及其子包下的所有类。
除了核心注解外,Spring Boot 还有许多常用的注解,如:
@Autowired
:自动装配,byType 方式。@Resource(name="name",type="type")
:自动装配,byName 方式。@Qualifier
:当有多个同一类型的 Bean 时,可以用 @Qualifier("name") 来指定。与 @Autowired 配合使用。@Component
:泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。@Repository
:用于标注数据访问组件,即 DAO 组件。@Service
:用于标注业务层组件。@Controller
:用于标注控制层组件(如struts中的action)。@RestController
:用于标注控制层组件,所有的方法都返回 json 格式的数据。
以上只是 Spring Boot 的一部分常用注解,更多注解的使用方法和场景,可以参考 Spring Boot 的官方文档或者相关教程。