Spring Boot (教程六: 注解列表)

本文详细解析了Spring Boot中常用注解的功能与应用场景,包括@SpringBootApplication、@Configuration、@EnableAutoConfiguration等,帮助开发者更好地理解和使用这些注解。

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

GitHub 地址:

https://github.com/asd821300801/Spring-Boot.git



@SpringBootApplication


这个配置等同于:@Configuration@EnableAutoConfiguration@ComponentScan 三个配置。
其中@ComponentScan让springBoot扫描到Configuration类并把它加入到程序上下文。

Eg:

package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *  SpringBootApplication注解
 * @author LingDu
 */
@SpringBootApplication
public class SpringbootHelloApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootHelloApplication.class, args);
    }
}


@Configuration


相当于传统的xml配置文件,如果有些第三方库需要用到xml文件,
建议仍然通过@Configuration类作为项目的配置主类——可以使用@ImportResource注解加载xml配置文件。

Eg:

package com.example.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 创建java类继承WebMvcConfigurerAdapter类,重写addInterceptors方法
 * @author LingDu
 */
@Configuration
public class InterceptorConfigurerAdapter extends WebMvcConfigurerAdapter {
    /**
     * 该方法用于注册拦截器
     * 可注册多个拦截器,多个拦截器组成一个拦截器链
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns 添加路径
        // excludePathPatterns 排除路径
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/*.*");
        super.addInterceptors(registry);
    }
}


@EnableAutoConfiguration


Spring Boot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置你的Spring应用。

例如:

如果你的classpath下存在HSQLDB,并且你没有手动配置任何数据库连接beans,那么我们将自动配置一个内存型(in-memory)数据库”。
你可以将@EnableAutoConfiguration或者@SpringBootApplication注解添加到一个@Configuration类上来选择自动配置。
如果发现应用了你不想要的特定自动配置类,你可以使用@EnableAutoConfiguration注解的排除属性来禁用它们。


@ComponentScan


表示将该类自动发现(扫描)并注册为Bean,可以自动收集所有的Spring组件,包括@Configuration类。
我们经常使用@ComponentScan注解搜索beans,并结合@Autowired注解导入。
如果没有配置的话,Spring Boot会扫描启动类所在包下以及子包下的使用了@Service,@Repository等注解的类。


@Component


可配合CommandLineRunner使用,在程序启动后执行一些基础任务。

package com.example.start;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 服务启动的时候运行
 * 创建一个类实现 CommandLineRunner 接口,重写 run(String... arg0)方法
 * @author LingDu
 */
@Component
@Order(value=2)
public class StartLoading implements CommandLineRunner {

    @Override
    public void run(String... arg0) throws Exception {
        System.out.println("优先级:2 ********* StartLoading:服务启动的时候运行,正在加载数据。。。。。");
    }
}


@RestController


@Controller@ResponseBody的合集,表示这是个控制器bean,
并且是将函数的返回值直接填入HTTP响应体中,是REST风格的控制器。

该注解是spring 4.0引入的。查看源码可知其包含了 @Controller@ResponseBody 注解。
我们可以理解为 @Controller的增强版。专门为响应内容式的 Controller 而设计的,可以直接响应对象为JSON。


@Controller


用于定义控制器类,在spring项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层)
一般这个注解在类中,通常方法需要配合注解@RequestMapping


@RequestMapping


提供路由信息,负责URL到Controller中的具体函数的映射。


@ResponseBody


该注解修饰的函数,会将结果直接填充到HTTP的响应体中,一般用于构建RESTful的api,该注解一般会配合@RequestMapping一起使用。

Eg:

package com.example.controller;

import java.util.ArrayList;
import java.util.List;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Spring Boot @ResponseBody 注解
 * @author LingDu
 */
@Controller
@RequestMapping(value=("/config"))
public class ConfigController {
    /**
     * 返回JSON数据
     * @return list
     */
    @RequestMapping("/valueToJson")
    public @ResponseBody List<Object> getValueToJson(){
        List<Object> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        return list;
    }
}


@Import


用来导入其他配置类。


@ImportResource


用来加载xml配置文件。


@Autowired


自动导入依赖的bean


@Service


一般用于修饰service层的组件


@Repository


使用@Repository注解可以确保DAO或者repositories提供异常转译
这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项。


@Bean


用@Bean标注方法等价于XML中配置的bean。

package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.DispatcherServlet;

import com.example.servlet.Servlet1;
/**
 * Spring Boot 教程一
 * Spring Boot 入门
 * @author LingDu
 */
@SpringBootApplication
@ServletComponentScan //使用注解的方式注册servlet需要在SpringbootHelloApplication.java中添加@ServletComponentScan注解
public class SpringbootHelloApplication {

   /**
     * 修改DispatcherServlet默认配置
     * @param dispatcherServlet2
     * @author LingDu
     */
    @Bean
    public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
        registration.getUrlMappings().clear();
        registration.addUrlMappings("*.action"); //只有*.action 的请求能通过
        registration.addUrlMappings("*.json");
        return registration;
    }

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


@Value


注入Spring boot application.properties配置的属性的值

    /**
     * 属性的值是通过配置文件读取的
     */
    @Value(value="${lingdu.secret}")  
    private String uuid;  

    @Value(value="${lingdu.number}")  
    private int randomID;  

    @Value(value="${lingdu.limitnumber}")  
    private int limitnumber;  


@Inject


等价于默认的@Autowired,只是没有required属性



@Qualifier


@Qualifier限定描述符除了能根据名字进行注入,但能进行更细粒度的控制如何选择候选者,具体使用方式如下:

    @Autowired
    @Qualifier(value = "demoInfoService") 
    private DemoInfoService demoInfoService;


@ServletComponentScan


使用注解的方式注册servlet需要在SpringbootHelloApplication.java中添加@ServletComponentScan注解

注意:注解加上后拦截器失效 去掉后 过滤器和监听器失效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值