Spring 注解

153 阅读22分钟

@SpringBootApplication

这个注解是 Spring Boot 项目的基石,创建 SpringBoot 项目之后会默认在主类加上。

@SpringBootApplication
public class SpringSecurityJwtGuideApplication {
      public static void main(java.lang.String[] args) {
        SpringApplication.run(SpringSecurityJwtGuideApplication.class, args);
    }
}

我们可以把 @SpringBootApplication看作是 @Configuration@EnableAutoConfiguration@ComponentScan 注解的集合。

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {

}

根据 SpringBoot 官网,这三个注解的作用分别是:

  • @EnableAutoConfiguration:启用 SpringBoot 的自动配置机制。
  • @ComponentScan: 扫描被@Component (@Service,@Controller)注解的 bean,注解默认会扫描该类所在的包下所有的类。
  • @Configuration:允许在 Spring 上下文中注册额外的 bean 或导入其他配置类。

Component,@Repositor,@Service, @Controller

我们一般使用 @Autowired 注解让 Spring 容器帮我们自动装配 bean。要想把类标识成可用于 @Autowired 注解自动装配的 bean 的类,可以采用以下注解实现:

  • @Component :通用的注解,可标注任意类为 Spring 组件。如果一个 Bean 不知道属于哪个层,可以使用@Component 注解标注。
  • @Repository : 对应持久层即 Dao 层,主要用于数据库相关操作。
  • @Service : 对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao 层。
  • @Controller : 对应 Spring MVC 控制层,主要用户接受用户请求并调用 Service 层返回数据给前端页面。

@Autowired

该注解是用来自动装配对象的,被注入进的类同样要被 Spring 容器管理,比如:Service 类注入到 Controller 类中。

@Autowired的装配顺序如下: image.png

  • 该注解默认情况下是按照类型装配的,也就是我们所说的byType方式。
  • 此外,@Autowired注解的required参数默认是true,表示开启自动装配,有些时候我们不想使用自动装配功能,可以将该参数设置成false
  • 上面byType方式主要针对相同类型的对象只有一个的情况,此时对象类型是唯一的,可以找到正确的对象。
  • 但如果相同类型的对象不只一个时,就会报错ConflictingBeanDefinitionException(类名称有冲突),从而导致整个项目启动不起来。 注意:这种情况不是相同类型的对象在Autowired时有两个导致的,二是因为spring的@Service方法不允许出现相同的类名,因为spring会将类名的第一个字母转换成小写,作为bean的名称,而默认情况下bean名称必须是唯一的。

产生这种问题通常有两种:
1.有两个相同名称的Bean对象。
2.一个接口有多个是实现类,因此注入的时候采用接口类型注入,导致Spring不知道你需要注入的是哪一个是实现类。
3.如果想要解决这种问题,这时可以改用按名称装配:byName,使用注解@Qualifier

@Autowired的高端玩法

高级用法一:自动装配多个实例。

public interface IUser { 
    void say();
}

@Service 
public class User1 implements IUser{ 
    @Override 
    public void say() {} 
}

@Service 
public class User2 implements IUser{ 
    @Override 
    public void say() { 
    } 
}

@Service 
public class UserService { 
    @Autowired private IUser user;
}
@Service public class UserService { 

    @Autowired 
    private List<IUser> userList; 
    @Autowired 
    private Set<IUser> userSet; 
    @Autowired 
    private Map<String, IUser> userMap; 
    
    public void test() { 
        System.out.println("userList:" + userList); 
        System.out.println("userSet:" + userSet); 
        System.out.println("userMap:" + userMap); 
    } }
  • userList、userSet和userMap都打印出了两个元素,说明@Autowired会自动把相同类型的IUser对象收集到集合中。

高级用法二:使用ApplicationContext来获取Bean实例。

web应用启动的顺序是:listener->filter->servlet

public class UserFilter implements Filter { 

    @Autowired 
    private IUser user; 

    @Override 
    public void init(FilterConfig filterConfig) throws ServletException { 
        user.say(); 
    }

    @Override 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    } 

    @Override 
        public void destroy() {
        } 
    } 

@Configuration 
public class FilterConfig { 
    @Bean 
    public FilterRegistrationBean filterRegistrationBean() { 
        FilterRegistrationBean bean = new FilterRegistrationBean(); 
        bean.setFilter(new UserFilter()); 
        bean.addUrlPatterns("/*"); 
        return bean; 
    } 
}

程序启动会报错:tomcat无法正常启动。springmvc的启动是在DisptachServlet里面做的,而它是在listenerfilter之后执行。如果我们想在listenerfilter里面@Autowired某个bean,肯定是不行的,因为filter初始化的时候,此时bean还没有初始化,无法自动装配。 如果工作当中真的需要这样做,我们该如何解决这个问题呢?

public class UserFilter implements Filter {

    private IUser user;
    
    @Override 
    public void init(FilterConfig filterConfig) throws ServletException { 
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
        this.user = ((IUser)(applicationContext.getBean("user1"))); 
        user.say(); 
    } 

    @Override 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    } 

    @Override 
    public void destroy() { } 
}

答案是使用WebApplicationContextUtils.getWebApplicationContext获取当前的ApplicationContext,再通过它获取到bean实例。

@Qualifier

该注解通常和@Autowired注解搭配使用,表示使用名称注入对象,需要指定一个bean的名称,通过bean名称就能找到需要装配的bean。

@Service("userService1")
public class UserService {
  ......
}

@Service("userService2")
public class UserService {
  ......
}

public class UserController {

   @Autowired
   @Qualifier("userService1")
   private UserService userService;
   
}

@Resource

@Resource的装配顺序如下:

image.png

  • 如果指定了name:

image.png

  • 如果指定了type:
  • 如果既没有指定name,也没有指定type: image.png

@RestController

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

  • 单独使用 @Controller 不加 @ResponseBody的话一般使用在要返回一个视图的情况,这种情况属于比较传统的 Spring MVC 的应用,对应于前后端不分离的情况。@Controller +@ResponseBody 返回 JSON 或 XML 形式数据。

@Import

@Import通过快速导入的方式实现把实例加入spring的IOC容器中。主要作用于类上

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {

	/**
	 * {@link Configuration @Configuration}, {@link ImportSelector},
	 * {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
	 */
	Class<?>[] value();

}

例如:

//实体类1
public class Bean01 {

    public Bean01(){
        System.out.println("Bean01构造器被调用");
    }
}

//实体类2
public class Bean02 {
    public Bean02(){
        System.out.println("Bean02构造器被调用");
    }
}

2.配置类 使用@Import导入Bean01和Bean02

@Configuration
@Import({Bean01.class,Bean02.class})
public class Configuration01 {
    public Configuration01(){
        System.out.println("Configuration01构造器被调用");
    }
}

3.测试

public class Test01 {
    public static void main(String[] args) {
        ApplicationContext applicationContext=new AnnotationConfigApplicationContext(Configuration01.class);
        for(String s:applicationContext.getBeanDefinitionNames()){
            System.out.println(s);
        }
    }
}

4.结果

//输出结果
Configuration01构造器被调用<br>
Bean01构造器被调用<br>
Bean02构造器被调用<br>
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory<br>
configuration01<br>
bean.Bean01<br>
bean.Bean02

@Bean

Spring的@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中。 SpringIOC 容器管理一个或者多个bean,这些bean都需要在@Configuration注解下进行创建,在一个方法上使用@Bean注解就表明这个方法需要交给Spring进行管理。

@Configuration
public class AppConfig {
    // 使用@Bean 注解表明myBean需要交给Spring进行管理
    // 未指定bean 的名称,默认采用的是 "方法名" + "首字母小写"的配置方式
    @Bean
    public MyBean myBean(){
        return new MyBean();
    }
}

public class MyBean {
    public MyBean(){
        System.out.println("MyBean Initializing");
    }
}

测试类SpringBeanApplicationTests

public class SpringBeanApplicationTests {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        context.getBean("myBean");
    }
}
//输出 : MyBean Initializing

@Bean 基本构成及其使用

@Bean 的基本构成

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {

	@AliasFor("name")
	String[] value() default {};

	@AliasFor("value")
	String[] name() default {};
        
        //此注解的方法表示自动装配的类型,返回一个`Autowire`类型的枚举
	Autowire autowire() default Autowire.NO;

	String initMethod() default "";

	String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;

}

@Bean不仅可以作用在方法上,也可以作用在注解类型上,在运行时提供注册。

value: name属性的别名,在不需要其他属性时使用,也就是说value 就是默认值。

name: 指定Bean的名称,或多个名称,主要的Bean的名称加别名。如果未指定,则bean的名称是带注解方法的名称。如果指定了,方法的名称就会忽略,如果没有其他属性声明的话,Bean的名称和别名可能通过value属性配置。

autowire: 的默认值为No,默认表示不通过自动装配。

// 枚举确定自动装配状态:即Bean是否应该使用setter注入由Spring容器自动注入其依赖项。
// 这是Spring DI的核心概念
public enum Autowire {

  // 常量,表示根本没有自动装配。
	NO(AutowireCapableBeanFactory.AUTOWIRE_NO),
	// 常量,通过名称进行自动装配
	BY_NAME(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME),
	// 常量,通过类型进行自动装配
	BY_TYPE(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE);

	private final int value;
	Autowire(int value) {
		this.value = value;
	}
	public int value() {
		return this.value;
	}
	public boolean isAutowire() {
		return (this == BY_NAME || this == BY_TYPE);
	}
}

initMethod: 这个可选择的方法在bean实例化的时候调用,InitializationBean接口允许bean在合适的时机通过设置注解的初始化属性从而调用初始化方法,InitializationBean 接口有一个定义好的初始化方法

void afterPropertiesSet() throws Exception;

Spring不推荐使用InitializationBean 来调用其初始化方法,因为它不必要地将代码耦合到Spring。Spring推荐使用@PostConstruct注解或者为POJO类指定其初始化方法这两种方式来完成初始化。

//不推荐使用
public class InitBean implements InitializingBean {
    public void afterPropertiesSet() {}
}

destroyMethod: 方法的可选择名称在调用bean示例在关闭上下文的时候,例如JDBC的close()方法,或者SqlSession的close()方法。DisposableBean 接口的实现允许在bean销毁的时候进行回调调用,DisposableBean 接口之后一个单个的方法

void destroy() throws Exception;

Spring不推荐使用DisposableBean的方式来初始化其方法,因为它会将不必要的代码耦合到Spring。作为替代性的建议,Spring 推荐使用@PreDestory注解或者为@Bean注解提供 destroyMethod 属性,

//不推荐使用
public class DestroyBean {
    public void cleanup() {}
}
//推荐使用
public class MyBean {

    public MyBean(){
        System.out.println("MyBean Initializing");
    }

    public void init(){
        System.out.println("Bean 初始化方法被调用");
    }

    public void destroy(){
        System.out.println("Bean 销毁方法被调用");
    }
}

@Configuration
public class AppConfig {

    @Bean(initMethod = "init", destroyMethod = "destroy")
    public MyBean myBean(){
        return new MyBean();
    }

}

修改一下测试类,测试其初始化方法和销毁方法在何时会被调用。

public class SpringBeanApplicationTests {

    public static void main(String[] args) {

        // ------------------------------ 测试一  ------------------------------
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        //context.getBean("myBean");
      
      	// 变体
        context.getBean("myBean");
        ((AnnotationConfigApplicationContext) context).destroy();
        //((AnnotationConfigApplicationContext) context).close();
    }
}

初始化方法在得到Bean的实例的时候就会被调用,销毁方法在容器销毁或者容器关闭的时候会被调用。

@Profile 注解

@Profile的作用是把一些meta-data进行分类,分成ActiveInActive这两种状态,然后你可以选择在active和在Inactive这两种状态下配置Bean,在Inactive状态通常的注解有一个 !操作符,通常写为:@Profile("!p"),这里的p是Profile的名字。

三种设置方式:

  • 可以通过ConfigurableEnvironment.setActiveProfiles()以编程的方式激活
  • 可以通过AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME (spring.profiles.active )属性设置为
  • 作为环境变量,或作为web.xml 应用程序的Servlet 上下文参数。也可以通过@ActiveProfiles 注解在集成测试中以声明方式激活配置文件。

作用域

  • 作为类级别的注释在任意类或者直接与@Component进行关联,包括@Configuration
  • 作为原注解,可以自定义注解
  • 作为方法的注解作用在任何方法

注意: 如果一个配置类使用了Profile标签或者@Profile作用在任何类中都必须进行启用才会生效,如果@Profile({"p1","!p2"}) 标识两个属性,那么p1是启用状态 而p2是非启用状态的。

现有一个POJO类为Subject学科类,里面有两个属性,一个是like(理科)属性,一个是wenke(文科)属性,分别有两个配置类,一个是AppConfigWithActiveProfile ,一个是AppConfigWithInactiveProfile,当系统环境是 "like"的时候就注册 AppConfigWithActiveProfile ,如果是 "wenke",就注册 AppConfigWithInactiveProfile,来看一下这个需求如何实现

// 学科
public class Subject {

    // 理科
    private String like;
    // 文科
    private String wenke;

   get and set ...

    @Override
    public String toString() {
        return "Subject{" +
                "like='" + like + ''' +
                ", wenke='" + wenke + ''' +
                '}';
    }
}

AppConfigWithActiveProfile.java 注册Profile 为like 的时候

@Profile("like")
@Configuration
public class AppConfigWithActiveProfile {

    @Bean
    public Subject subject(){
        Subject subject = new Subject();
        subject.setLike("物理");
        return subject;
    }

}

AppConfigWithInactiveProfile.java 注册Profile 为wenke 的时候

@Profile("wenke")
@Configuration
public class AppConfigWithInactiveProfile {

    @Bean
    public Subject subject(){
        Subject subject = new Subject();
        subject.setWenke("历史");
        return subject;
    }
}

修改一下对应的测试类,设置系统环境,当Profile 为like 和 wenke 的时候分别注册各自对应的属性

// ------------------------------ 测试 profile  ------------------------------
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 激活 like 的profile
context.getEnvironment().setActiveProfiles("like");
context.register(AppConfigWithActiveProfile.class,AppConfigWithInactiveProfile.class);
context.refresh();
Subject subject = (Subject) context.getBean("subject");
System.out.println("subject = " + subject);

把context.getEnvironment().setActiveProfiles("wenke") 设置为wenke,观察其对应的输出内容发生了变化,这就是@Profile的作用,有一层可选择性注册的意味。

@DependsOn

指当前Bean所依赖的Bean。任何指定的Bean都能保证在此Bean创建之前由IOC容器创建。在Bean没有通过属性或构造函数参数显式依赖于另一个Bean的情况下很少使用,可能直接使用在任何直接或者间接使用Component 或者Bean注解表明的类上。来看一下具体的用法

新建三个Bean,分别是FirstBean、SecondBean、ThirdBean三个普通的Bean,新建AppConfigWithDependsOn并配置它们之间的依赖关系

public class FirstBean {

    @Autowired
    private SecondBean secondBean;

    @Autowired
    private ThirdBean thirdBean;

    public FirstBean() {
        System.out.println("FirstBean Initialized via Constuctor");
    }
}

public class SecondBean {

    public SecondBean() {
        System.out.println("SecondBean Initialized via Constuctor");
    }
}

public class ThirdBean {

    public ThirdBean() {
        System.out.println("ThirdBean Initialized via Constuctor");
    }
}

@Configuration
public class AppConfigWithDependsOn {

    @Bean("firstBean")
    @DependsOn(value = {
            "secondBean",
            "thirdBean"
    })
    public FirstBean firstBean() {
        return new FirstBean();
    }

    @Bean("secondBean")
    public SecondBean secondBean() {
        return new SecondBean();
    }

    @Bean("thirdBean")
    public ThirdBean thirdBean() {
        return new ThirdBean();
    }
}

使用测试类进行测试,如下

// ------------------------------ 测试 DependsOn  ------------------------------
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfigWithDependsOn.class);
context.getBean(FirstBean.class);
context.close();

输出 :

SecondBean Initialized via Constuctor
ThirdBean Initialized via Constuctor
FirstBean Initialized via Constuctor

由于firstBean的创建过程首先需要依赖secondBean 和 thirdBean的创建,所以secondBean首先被加载其次是thirdBean最后是firstBean。 如果把@DependsOn注解加在AppConfigWithDependsOn 类上则它们的初始化顺序就会变为firstBeansecondBeanthirdBean

@Primary

Primary可以理解为默认优先选择,同时不可以同时设置多个,内部实质是设置BeanDefinitionprimary属性。 当一个接口有2个不同实现时,使用@Autowired注解时会报org.springframework.beans.factory.NoUniqueBeanDefinitionException异常信息,此时则可以使用该注解可默认优先选择,但是该注解不可以同时设置多个。

public interface Singer {
    void sing();
}


@Primary
@Component("operaSinger")
public class OperaSinger implements Singer {
    @Override
    public void sing() {
        System.out.println("OperaSinger");
    }
}

@Component("metalSinger")
public class MetalSinger implements Singer{

    @Override
    public void sing() {
        System.out.println("MetalSinger");
    }
}

//测试
@Resource
private Singer singer;
@Test
void contextLoads() {
    singer.sing();
}

//执行结果:OperaSinger

@Scope

Spring中对于Bean的默认处理都是单例的,我们通过上下文容器getBean方法拿到Bean容器,并对其进行实例化,这个实例化的过程其实只进行一次,后面再次获取的对象都是同一个对象,也就相当于这个Bean的实例在IOC容器中是public的,对于所有的Bean请求来讲都可以共享此Bean 那么假如我不想把这个Bean被所有的请求共享或者说每次调用我都想让它生成一个Bean实例该怎么处理呢?

多例Bean

Bean的非单例原型范围会使每次发出对该特定Bean的请求时都创建新的Bean实例,也就是说Bean被注入另一个Bean,或者通过对容器的getBean()方法调用来请求它,可以用如下图来表示:

例如AppConfigWithAliasAndScope配置类,用来定义多例的bean,

@Configuration
public class AppConfigWithAliasAndScope {

    /**
     * 为myBean起两个名字,b1 和 b2
     * @Scope 默认为 singleton,但是可以指定其作用域
     * prototype 是多例的,即每一次调用都会生成一个新的实例。
     */
    @Bean({"b1","b2"})
    @Scope("prototype")
    public MyBean myBean(){
        return new MyBean();
    }
}

测试一下多例的情况:

// ------------------------------ 测试scope  ------------------------------
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfigWithAliasAndScope.class);
MyBean myBean = (MyBean) context.getBean("b1");
MyBean myBean2 = (MyBean) context.getBean("b2");
System.out.println(myBean);
System.out.println(myBean2);

其他情况

除了多例的情况下,Spring还为我们定义了其他情况:

ScopeDescriptionn
singleton默认单例的bean定义信息,对于每个IOC容器来说都是单例对象
prototypebean对象的定义为任意数量的对象实例
requestbean对象的定义为一次HTTP请求的生命周期,也就是说,每个HTTP请求都有自己的bean实例,它是在单个bean定义的后面创建的。仅仅在web-aware的上下文中有效
sessionbean对象的定义为一次HTTP会话的生命周期。仅仅在web-aware的上下文中有效
applicationbean对象的定义范围在ServletContext生命周期内。仅仅在web-aware的上下文中有效
websocketbean对象的定义为WebSocket的生命周期内。仅仅在web-aware的上下文中有效

singleton和prototype 一般都用在普通的Java项目中,而request、session、application、websocket都用于web应用中。

request、session、application、websocket的作用范围

你可以体会到request、session、application、websocket的作用范围在当你使用web-aware的ApplicationContext应用程序上下文的时候,比如XmlWebApplicationContext的实现类。如果你使用了像 是ClassPathXmlApplicationContext的上下文环境时,就会抛出IllegalStateException因为Spring不认识这个作用范围。

@Lazy

@Lazy : 表明一个Bean是否延迟加载,可以作用在方法上,表示这个方法被延迟加载;可以作用在@Component(或者由@Component作为原注解) 注释的类上,表明这个类中所有的Bean都被延迟加载。如果没有@Lazy注释,或者@Lazy被设置为false,那么该Bean就会急切渴望被加载;除了上面两种作用域,@Lazy还可以作用在@Autowired@Inject注释的属性上,在这种情况下,它将为该字段创建一个惰性代理,作为使用ObjectFactoryProvider的默认方法。下面来演示一下:

@Lazy
@Configuration
@ComponentScan(basePackages = "com.spring.configuration.pojo")
public class AppConfigWithLazy {

    @Bean
    public MyBean myBean(){
        System.out.println("myBean Initialized");
        return new MyBean();
    }

    @Bean
    public MyBean IfLazyInit(){
        System.out.println("initialized");
        return new MyBean();
    }
}

测试类

public class SpringConfigurationApplication {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfigWithLazy.class);
        // 获取启动过程中的bean 定义的名称
        for(String str : context.getBeanDefinitionNames()){
            System.out.println("str = " + str);
        }
    }
}

输出你会发现没有关于bean的定义信息,但是当把@Lazy注释拿掉,你会发现输出了关于bean的初始化信息。

@Configuration

一般用来声明配置类,可以使用 @Component注解替代,不过使用Configuration注解声明配置类更加语义化。

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}

@RequestParam

public @interface RequestParam {

   @AliasFor("name")
   String value() default "";//指定参数名称

   @AliasFor("value")
   String name() default "";//指定参数名称

   //默认为true,如果请求中缺少参数,则会导致抛出异常。 
   //如果请求中不存在该参数,则如果您更喜欢null值,请将其切换为false。
   boolean required() default true;

   //当没有提供参数或参数值为空时,@RequestParam 中的 defaultValue 属性值将会作为默认的参数值。
   //如果提供了默认值会隐式地将 required 设置为false
   String defaultValue() default ValueConstants.DEFAULT_NONE;

}
  • 适用于GET,POST请求方式。

  • 一个方法当中可以使用多次。- @RequestBody()@RequestParam()可以同时使用。

  • 当我们使用POST时,一般会将参数写入请求体,即body内,使用的编码格式为application/x-www-form-urlencoded

  • 用来处理Content-Type: 为 form-data或者application/x-www-form-urlencoded编码的内容,(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)或者请求URL?后面的参数均可以使用该注解接收。

  • @RequestParam可以接受简单类型的属性,也可以接受对象类型。 其实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。

  • Content-Type: application/x-www-form-urlencoded的请求中, get 方式中queryString的值,和post方式中 body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以该注解可以获取的到。

@RequestPart

1.@RequestPart这个注解用在multipart/form-data表单提交请求的方法上。

2.支持的请求方法的方式MultipartFile,属于Spring的MultipartResolver类。这个请求是通过http协议传输的。

3.@RequestParam也同样支持multipart/form-data请求。

4.他们最大的不同是,当请求方法的请求参数类型不再是String类型的时候。

5.@RequestParam适用于name-valueString类型的请求域,@RequestPart适用于复杂的请求域(像JSON,XML)。

@RequestBody

public @interface RequestBody {

   //是否需要请求体内容,默认为true。如果没有请求体内容,则会引发异常。
   //如果您希望在请求体内容为null时传递null,请将其切换为false 。
   boolean required() default true;

}
  • 主要用来接收Content-Typeapplication/json类型,来自HTTP请求体中的数据,GET方式无请求体,因此必须以POST方式提交数据。

  • @RequestBody注解一次性将请求体中的数据全部取出来,因此在一个请求当中建议只有一个。但是可以有多个@RequestParam(),

  • @RequestBody()@RequestParam()可以同时使用。

  • @RequestBody一般用于接收请求体当中的参数,在后端注解对应的类在将HTTP的输入流(含请求体)装配到目标类时,会根据json字符串中的key来匹配对应实体类的属性,如果匹配一致且json中的该key对应的值符合(或可转换为) 实体类的对应属性的类型要求时,会调用实体类的setter方法将值赋给该属性。

@PathVariable

@PathVariable用于获取URL路径参数

举个简单的例子:

@GetMapping("/klasses/{klassId}/teachers")
public List<Teacher> getKlassRelatedTeachers(
         @PathVariable("klassId") Long klassId,
         @RequestParam(value = "type", required = false) String type ) {
...
}

如果我们请求的 url 是:/klasses/{123456}/teachers?type=web

那么我们服务获取到的数据就是:klassId=123456,type=web

@Transient

java 的transient关键字的作用是需要实现Serilizable接口,将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会序列化到指定的目的地中。

@Transient则将字段标记为映射框架的瞬态。因此,该属性将不会被持久化,也不会被映射框架进一步检查。 @transient就是在给某个Bean对象上需要添加个属性,但是这个属性你又不希望给存到数据库中去,仅仅是做个临时变量,用一下,不修改已经存在数据库的数据的数据结构。就可以使用这个注解。

@value

  1. 支持如下方式的注入:
  • 注入普通字符
  • 注入操作系统属性
  • 注入表达式结果
  • 注入其它bean属性
  • 注入文件资源
  • 注入网站资源
  • 注入配置文件
  1. @Value三种情况的用法。
  • ${}是去找外部配置的参数,将值赋过来
  • #{}是SpEL表达式,去寻找对应变量的内容
  • #{}直接写字符串就是将字符串的值注入进去

application.yml内容如下:

level:
  ether:
    tx-size: 10
    range:
      - min: 0
        max: 0.1
        value: 1
      - min: 0.1
        max: 1
        value: 2
      - min: 1
        max: 2
        value: 3
      - min: 2
        max: 5
        value: 4
      - min: 5
        max: 7
        value: 5
      - min: 7
        max: 10
        value: 6

使用 @Value("${property}") 读取比较简单的配置信息:

案例:

@Value("${level.ether.tx-size}")
Integer size;

结果: size:10

@ConfigurationProperties

application.yml内容如下:

level:
  ether:
    tx-size: 10
    range:
      - min: 0
        max: 0.1
        value: 1
      - min: 0.1
        max: 1
        value: 2
      - min: 1
        max: 2
        value: 3
      - min: 2
        max: 5
        value: 4
      - min: 5
        max: 7
        value: 5
      - min: 7
        max: 10
        value: 6

通过@ConfigurationProperties读取配置信息并与 bean 绑定。

@Configuration
@ConfigurationProperties(prefix = "level.ether")
@Data
public class EtherLevelConfig {
    private List<Range> range = new LinkedList<>();
    private Integer txSize;

    @Data
    @NoArgsConstructor
    public static class Range {
        private BigDecimal min;
        private BigDecimal max;
        private BigDecimal value;
    }
}

@CookieValue

public @interface CookieValue {

   //参数名称
   String value() default "";
   
   //参数名称
   @AliasFor("value")
   String name() default "";
   
   //是否需要 cookie。默认为true ,如果请求中缺少 cookie,则会引发异常。
   //如果请求中不存在cookie,如果您更喜欢null值,请将其切换为false。
   boolean required() default true;

   //提供默认值会隐式地将required设置为false 。
   String defaultValue() default ValueConstants.DEFAULT_NONE;

}

案例:

@Controller
public class handleCookies {

	@GetMapping("/getCookie")
	public String getCookieValue(@CookieValue("JSESSIONID") String jId) {
		System.out.println(jId);
		return "success";
	}

}
  • 以前在 Servlet 中获取某个指定的 Cookie 的值使用 Cookie[] cookies = request.getCookies(); 来获得所有 Cookie 的值,然后再遍历。

  • 此注解用方法的参数上,可以把HTTP Cookie中相应名称的Cookie绑定上去。

  • Cookiehttp请求中nameJSESSIONIDCookie值。

@Transactional

在要开启事务的方法上使用@Transactional注解即可!

@Transactional(rollbackFor = Exception.class)
public void save() {
  ......
}

我们知道 Exception 分为运行时异常 RuntimeException 和非运行时异常。在@Transactional注解中如果不配置rollbackFor属性,那么事物只会在遇到RuntimeException的时候才会回滚,加上rollbackFor=Exception.class,可以让事物在遇到非运行时异常时也回滚。

@Transactional 注解一般用在可以作用在或者方法上。

  • 作用于类:当把@Transactional 注解放在类上时,表示所有该类的public 方法都配置相同的事务属性信息。
  • 作用于方法:当类配置了@Transactional,方法也配置了@Transactional,方法的事务会覆盖类的事务配置信息。

@ControllerAdvice

@ControllerAdvice :注解定义全局异常处理类

@ExceptionHandler

@ExceptionHandler :注解声明异常处理方法

@JsonIgnore

@JsonIgnore一般用于类的属性上,过滤掉特定字段不返回或者不解析。

作用: 在json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。

使用方法: 一般标记在属性或者方法上,返回的json数据即不包含该属性。

注解失效:如果注解失效,可能是因为你使用的是fastJson,尝试使用对应的注解来忽略字段,注解为:@JSONField(serialize = false),使用方法一样。

public class User {

    private String userName;
    private String fullName;
    private String password;
   //生成json时将userRoles属性过滤
    @JsonIgnore
    private List<UserRole> userRoles = new ArrayList<>();
}

@JsonIgnoreProperties

@JsonIgnoreProperties 作用在类上用于过滤掉特定字段不返回或者不解析。

//生成json时将userRoles属性过滤
@JsonIgnoreProperties({"userName"},{"fullName"})
public class User {

    private String userName;
    private String fullName;
    private String password;
    private List<UserRole> userRoles = new ArrayList<>();
}

@JsonSerialize

此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点。

@JsonFormat

@JsonFormat:用来表示json序列化的一种格式或者类型,并不仅仅仅限于日期,也可以解决Long类型主键从前端传回后端丢失精度的问题。

案例:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private Date date;

@JsonFormat(shape = JsonFormat.Shape.STRING)
private Long id;
  • shape:表示序列化后的一种类型

@JsonProperty

@JsonProperty可以指定某个属性和json映射的名称。例如我们有个json字符串为{“user_name”:”aaa”}, 而java中命名要遵循驼峰规则,则为userName,这时通过@JsonProperty注解来指定两者的映射规则即可。这个注解也比较常用。 public class SomeEntity { @JsonProperty("user_name") private String userName; }

@JsonUnwrapped_扁平化对象

@Getter
@Setter
@ToString
public class Account {
    @JsonUnwrapped
    private Location location;
    @JsonUnwrapped
    private PersonInfo personInfo;

  @Getter
  @Setter
  @ToString
  public static class Location {
     private String provinceName;
     private String countyName;
  }
  @Getter
  @Setter
  @ToString
  public static class PersonInfo {
    private String userName;
    private String fullName;
  }
}

未扁平化之前:

{
    "location": {
        "provinceName":"湖北",
        "countyName":"武汉"
    },
    "personInfo": {
        "userName""coder1234",
        "fullName""shaungkou"
    }
}

使用@JsonUnwrapped 扁平对象之后:

@Getter
@Setter
@ToString
public class Account {
    @JsonUnwrapped
    private Location location;
    @JsonUnwrapped
    private PersonInfo personInfo;
    ......
}
{
  "provinceName":"湖北",
  "countyName":"武汉",
  "userName""coder1234",
  "fullName""shaungkou"
}

只在序列化情况下生效的注解

@JsonPropertyOrder

在将 java pojo 对象序列化成为 json 字符串时,使用 @JsonPropertyOrder 可以指定属性在 json 字符串中的顺序。

@JsonInclude

在将 java pojo 对象序列化成为 json 字符串时,使用 @JsonInclude 注解可以控制在哪些情况下才将被注解的属性转换成 json,例如只有属性不为 null 时。

@JsonInclude(JsonInclude.Include.NON_NULL)

这个注解放在类头上,返给前端的json里就没有null类型的字段,即实体类与json互转的时候 属性值为null的不参与序列化。 另外还有很多其它的范围,例如 NON_EMPTY、NON_DEFAULT等

在反序列化情况下生效的注解

@JsonSetter

@JsonSetter 标注于 setter 方法上,类似 @JsonProperty ,也可以解决 json 键名称和 java pojo 字段名称不匹配的问题。

SpringAop相关注解

Spring支持AspectJ的注解式切面编程。

@Aspect 声明一个切面

@After 在方法执行之后执行(方法上)

@Before 在方法执行之前执行(方法上)

@Around 在方法执行之前与之后执行(方法上)

@PointCut 声明切点

在java配置类中使用@EnableAspectJAutoProxy注解开启Spring对AspectJ代理的支持

Spring异步的注解

@EnableAsync作用于启动类上通过此注解开启对异步任务的支持; @Async作用在方法上在实际执行的bean方法使用该注解来声明其是一个异步任务(方法上或类上所有的方法都将异步,前提需要@EnableAsync开启异步任务)

Spring定时任务注解

@EnableScheduling作用于启动类上开启定时任务的支持

@Scheduled来申明这是一个任务,包括cron,fixDelay,fixRate等类型(方法上,需先开启计划任务的支持)

一些常用的字段验证的注解

  • @NotEmpty 被注释的字符串的不能为 null 也不能为空
  • @NotBlank 被注释的字符串非 null,并且必须包含一个非空白字符
  • @Null 被注释的元素必须为 null
  • @NotNull 被注释的元素必须不为 null
  • @AssertTrue 被注释的元素必须为 true
  • @AssertFalse 被注释的元素必须为 false
  • @Pattern(regex=,flag=)被注释的元素必须符合指定的正则表达式
  • @Email 被注释的元素必须是 Email 格式。
  • @Min(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值
  • @Max(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值
  • @DecimalMin(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值
  • @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
  • @Size(max=, min=)被注释的元素的大小必须在指定的范围内
  • @Digits (integer, fraction)被注释的元素必须是一个数字,其值必须在可接受的范围内
  • @Past被注释的元素必须是一个过去的日期
  • @Future 被注释的元素必须是一个将来的日期
  • ......

我们在需要验证的方法参数上加上了@Valid注解或者在该类上加上@Validated 注解,如果验证失败,它将抛出MethodArgumentNotValidException