Spring注解大全

目录

@Controller

@RestController

@Service

@Autowired

@RequestMapping

@RequestParam

@NonNullApi

@NonNullFields

@Cacheable

@CacheEvict

@Resource

@Qualifier

@PostConstruct

@PreDestroy

@Repository

@Component

@Scope

@Bean

@SessionAttributes

@Required

@Qualifier

@Transactional

@Aspect

@Pointcut

@AfterReturning

@Around

@AfterThrowing

@After

         @Value注解作用

@Import

@DependsOn

@Profile


@Controller

标识一个该类是Spring MVC controller处理器,用来创建处理http请求的对象.

@Controller
public class TestController {
        @RequestMapping("/test")
        public String test(Map<String,Object> map){
            return "hello";
        }
}

@RestController

Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。

@RestController
public class TestController {
	@RequestMapping("/test")
	public String test(Map<String,Object> map){

		return "hello";
	}
}

@Service

用于标注业务层组件,说白了就是加入你有一个用注解的方式把这个类注入到spring配置中

@Service
public class TestService {
        public String test(Map<String,Object> map){
            return "hello";
        }
}

@Autowired

用来装配bean,都可以写在字段上,或者方法上。
默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,例如:@Autowired(required=false)

@RestController
public class TestController {

        @Autowired(required=false)
        private TestService service;

        @RequestMapping("/test")
        public String test(Map<String,Object> map){

            return "hello";
        }
}

@RequestMapping

类定义处: 提供初步的请求映射信息,相对于 WEB 应用的根目录。
方法处: 提供进一步的细分映射信息,相对于类定义处的 URL。

@RestController
public class TestController {
        @RequestMapping("/test")
        public String test(Map<String,Object> map){

            return "hello";
        }
}

method 主要用来定义接收浏览器发来的何种请求(GET(查)、POST(增)、PUT(改)、DELETE(删)

@Controller
@RequestMapping(path = "/user")
public class UserController {
 
	@RequestMapping(path = "/login", method=RequestMethod.GET)
	public String login() {
		return "success";
	}

其他详情说明参考:@RequestMapping用法详解_江南雨-CSDN博客_@requestmapping

@RequestParam

用于将请求参数区数据映射到功能处理方法的参数上
例如

public Resp test(@RequestParam Integer id){
     return Resp.success(customerInfoService.fetch(id));
}

这个id就是要接收从接口传递过来的参数id的值的,如果接口传递过来的参数名和你接收的不一致,也可以如下

public Resp test(@RequestParam(value="course_id") Integer id){
	return Resp.success(customerInfoService.fetch(id));
}

其中course_id就是接口传递的参数,id就是映射course_id的参数名

@NonNull

标注在方法、字段、参数上,表示对应的值不能为空。

@Nullable

标注在方法、字段、参数上,表示对应的值可以为空。

@NonNullApi

程序包级别的 注解,它声明非 null 为参数和返回值的默认行为。


@NonNullFields

程序包级别的 注解,它声明非 null 为字段的默认行为。

@ModelAttribute

使用地方有三种:

1. 标记在方法上。

标记在方法上,会在每一个@RequestMapping标注的方法前执行,如果有返回值,则自动将该返回值加入到ModelMap中。

A.在有返回的方法上:
当ModelAttribute设置了value,方法返回的值会以这个value为key,以参数接受到的值作为value,存入到Model中,如下面的方法执行之后,最终相当于 model.addAttribute(“user_name”, name);假如 @ModelAttribute没有自定义value,则相当于
model.addAttribute(“name”, name);

@ModelAttribute(value="user_name")
public String before2(@RequestParam(required = false) String name, Model model) {
	System.out.println("进入了2:" + name);
	return name;
}

B.在没返回的方法上:

需要手动model.add方法

@ModelAttribute
public void before(@RequestParam(required = false) Integer age, Model model) {
    model.addAttribute("age", age);
    System.out.println("进入了1:" + age);
}

我们在当前类下建一个请求方法:

@RequestMapping(value="/mod")
public Resp mod(
		@RequestParam(required = false) String name,
		@RequestParam(required = false) Integer age, 
		Model model){
	System.out.println("进入mod");
	System.out.println("参数接受的数值{name="+name+";age="+age+"}");
	System.out.println("model传过来的值:"+model);
	return Resp.success("1");
}

在浏览器中输入访问地址并且加上参数:
http://localhost:8081/api/test/mod?name=我是小菜&age=12

最终输出如下:

进入了1:40
进入了2:我是小菜
进入mod
参数接受的数值{name=我是小菜;age=12}
model传过来的值:{age=40, user_name=我是小菜}

2. 标记在方法的参数上。

标记在方法的参数上,会将客户端传递过来的参数按名称注入到指定对象中,并且会将这个对象自动加入ModelMap中,便于View层使用.
我们在上面的类中加入一个方法如下

@RequestMapping(value="/mod2")
public Resp mod2(@ModelAttribute("user_name") String user_name, 
		@ModelAttribute("name") String name,
		@ModelAttribute("age") Integer age,Model model){
	System.out.println("进入mod2");
	System.out.println("user_name:"+user_name);
	System.out.println("name:"+name);
	System.out.println("age:"+age);
	System.out.println("model:"+model);
	return Resp.success("1");
}

在浏览器中输入访问地址并且加上参数:
http://localhost:8081/api/test/mod2?name=我是小菜&age=12
最终输出:

进入了1:40
进入了2:我是小菜
进入mod2
user_name:我是小菜
name:我是小菜
age:40
model:{user_name=我是小菜, org.springframework.validation.BindingResult.user_name=org.springframework.validation.BeanPropertyBindingResult: 0 errors, name=我是小菜, org.springframework.validation.BindingResult.name=org.springframework.validation.BeanPropertyBindingResult: 0 errors, age=40, org.springframework.validation.BindingResult.age=org.springframework.validation.BeanPropertyBindingResult: 0 errors}

从结果就能看出,用在方法参数中的@ModelAttribute注解,实际上是一种接受参数并且自动放入Model对象中,便于使用。


@Cacheable

用来标记缓存查询。可用用于方法或者类中,

当标记在一个方法上时表示该方法是支持缓存的,
当标记在一个类上时则表示该类所有的方法都是支持缓存的。

参数列表

参数解释例子
value名称@Cacheable(value={”c1”,”c2”}
keykey@Cacheable(value=”c1”,key=”#id”)
condition条件@Cacheable(value=”c1”,condition=”#id=1”)

比如@Cacheable(value=”UserCache”) 标识的是当调用了标记了这个注解的方法时,逻辑默认加上从缓存中获取结果的逻辑,如果缓存中没有数据,则执行用户编写查询逻辑,查询成功之后,同时将结果放入缓存中。
但凡说到缓存,都是key-value的形式的,因此key就是方法中的参数(id),value就是查询的结果,而命名空间UserCache是在spring*.xml中定义.

@Cacheable(value="UserCache")// 使用了一个缓存名叫 accountCache   
public Account getUserAge(int id) {  
     //这里不用写缓存的逻辑,直接按正常业务逻辑走即可,
     //缓存通过切面自动切入  
    int age=getUser(id);   
     return age;   
} 

@CacheEvict

用来标记要清空缓存的方法,当这个方法被调用后,即会清空缓存。@CacheEvict(value=”UserCache”)

参数列表

参数解释例子
value名称@CachEvict(value={”c1”,”c2”}
keykey@CachEvict(value=”c1”,key=”#id”)
condition缓存的条件,可以为空
allEntries是否清空所有缓存内容@CachEvict(value=”c1”,allEntries=true)
beforeInvocation是否在方法执行前就清空@CachEvict(value=”c1”,beforeInvocation=true)

@Resource

@Resource的作用相当于@Autowired
只不过@Autowired按byType自动注入,
而@Resource默认按 byName自动注入罢了。

@Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
 

@Resource装配顺序:

1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;

@Qualifier

当一个接口有多个实现类时,就可以用此注解表明哪个实现类才是我们所需要的,名称为我们之前定义@Service注解的名称之一。

@PostConstruct

用来标记是在项目启动的时候执行这个方法。用来修饰一个非静态的void()方法
也就是spring容器启动时就执行,多用于一些全局配置、数据字典之类的加载

被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。PreDestroy()方法在destroy()方法执行执行之后执
 

@PreDestroy

被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前

@Repository

用于标注数据访问组件,即DAO组件

@Component

把普通pojo实例化到spring容器中,相当于配置文件中的 <bean id="" class=""/>
它泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类。
此外,被@controller 、@service、@repository 、@component 注解的类,都会把这些类纳入进spring容器中进行管理

@Scope

用来配置 spring bean 的作用域,它标识 bean 的作用域。
默认值是单例

prototype原型模式:
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)这个是说在每次注入的时候回自动创建一个新的bean实例

singleton单例模式:
@Scope(value=ConfigurableBeanFactory.SCOPE_SINGLETON)单例模式,在整个应用中只能创建一个实例

globalsession模式:
@Scope(value=WebApplicationContext.SCOPE_GLOBAL_SESSION)全局session中的一般不常用

@Scope(value=WebApplicationContext.SCOPE_APPLICATION)在一个web应用中只创建一个实例

request模式:
@Scope(value=WebApplicationContext.SCOPE_REQUEST)在一个请求中创建一个实例

session模式:
@Scope(value=WebApplicationContext.SCOPE_SESSION)每次创建一个会话中创建一个实例

@Bean

常用于被@Configuration修饰的类中,用于产生一个bean的方法,并且交给Spring容器管理,相当于配置文件中的 <bean id="" class=""/>

@SessionAttributes

默认情况下Spring MVC将模型中的数据存储到request域中。当一个请求结束后,数据就失效了。如果要跨页面使用。那么需要使用到session。而@SessionAttributes注解就可以使得模型中的数据存储一份到session域中

参数:

  1. names:这是一个字符串数组。里面应写需要存储到session中数据的名称。
  2. types:根据指定参数的类型,将模型中对应类型的参数存储到session中
  3. value:和names是一样的。
@Controller
@SessionAttributes(value={"names"},types={Integer.class})
public class ScopeService {
        @RequestMapping("/testSession")
        public String test(Map<String,Object> map){
            map.put("names", Arrays.asList("a","b","c"));
            map.put("age", 12);
            return "hello";
        }
}

@Required

适用于bean属性setter方法,并表示受影响的bean属性必须在XML配置文件在配置时进行填充。否则,容器会抛出一个BeanInitializationException异常。

@Qualifier

当你创建多个具有相同类型的 bean 时,并且想要用一个属性只为它们其中的一个进行装配,在这种情况下,你可以使用 @Qualifier 注释和 @Autowired 注释通过指定哪一个真正的 bean 将会被装配来消除混乱

@Transactional

事务管理一般有编程式和声明式两种,编程式是直接在代码中进行编写事物处理过程,而声名式则是通过注解方式或者是在xml文件中进行配置,相对编程式很方便。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

JDBC事务 

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
 </bean>

<tx:annotation-driven transaction-manager="transactionManager" />

 Hibernate事务

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
<tx:annotation-driven transaction-manager="transactionManager" />

 JPA事务

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
<tx:annotation-driven transaction-manager="transactionManager" />

Java原生API事务 

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
        <property name="transactionManagerName" value="java:/TransactionManager" />
    </bean>
<tx:annotation-driven transaction-manager="transactionManager" />

spring所有的事务管理策略类都继承自org.springframework.transaction.PlatformTransactionManager接口

@Aspect

作用是标记一个切面类(spring不会将切面注册为Bean也不会增强,但是需要扫描)

<!-- 扫描Aspect增强的类 -->
<context:component-scan base-package="">
    <context:include-filter type="annotation"
        expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>

<!-- 开启@AspectJ注解支持 -->
<aop:aspectj-autoproxy/>
<?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
         xmlns:context="http://www.springframework.org/schema/context"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--包扫描-->    <context:component-scan base-package="com.cn"/>
    <!--开启ioc注解-->
    <context:annotation-config/>
    <!--开启aop注解-->
    <aop:aspectj-autoproxy/>
 </beans>

@Pointcut

定义切点,切点表达式(execution(权限访问符 返回值类型 方法所属的类名包路径.方法名(形参类型) 异常类型))

@Before

前置增强,配合@Pointcut一起使用

@AfterReturning

后置增强,配合@Pointcut一起使用

@Around

环绕增强,配合@Pointcut一起使用

@AfterThrowing

异常抛出增强,配合@Pointcut一起使用

@After

最终增强(最后执行),配合@Pointcut一起使用

@Aspect
@Component
public class AfterThrowingAspect {

    //全路径execution(public String com.cnblogs.hellxz.test.Test.access(String,String))
    @Pointcut("execution(* com.cnblogs.hellxz.test.*.*(..))")
    public void pointcut() {}
     
    //前置增强
    @Before("pointcut()")
    public void before(JoinPoint jp){
        System.out.println("我是方法"+jp.getSignature().getName()+"的前置增强!");      
    }

     //后置增强
     @AfterReturning(value = "pointcut()",returning = "obj")
     public void afterReturning(JoinPoint jp,Object obj){
         System.out.println("我是方法"+jp.getSignature().getName()+"的后置增强!"+",返回值为"+obj);
     }

     //环绕增强
     @Around("pointcut()")
     public void around(ProceedingJoinPoint jp) throws Throwable {
         System.out.println("我是环绕增强中的前置增强!");
         Object proceed = jp.proceed();//植入目标方法
         System.out.println("我是环绕增强中的后置增强!");
     }

     //异常抛出增强
     @AfterThrowing(value = "pointcut()",throwing = "e")
     public void error(JoinPoint jp,Exception e){
         System.out.println("我是异常抛出增强"+",异常为:"+e.getMessage());
     }

     //最终增强
     @After("pointcut()")
     public void after(JoinPoint jp){
         System.out.println("我是最终增强");
     }
}

@Value注解作用

该注解的作用是将我们配置文件的属性读出来,有@Value(“${}”)@Value(“#{}”)两种方式:

@Value的值有两类:
1. ${property : default_value}
2. #{obj.property? : default_value}
第一个注入的是外部配置文件对应的property,第二个则是SpEL表达式对应的内容。 那个
default_value,就是前面的值为空时的默认值。注意二者的不同,#{}里面那个obj代表对象

注入数组和列表形式:

/**
 * 注入数组(自动根据","分割)
 */
@Value("${tools}")
private String[] toolArray;

/**
 * 注入列表形式(自动根据","分割)
 */
@Value("${tools}")
private List<String> toolList;

SpEL表达式具体实例场景的应用:

/**
 * 注入普通字符串,相当于直接给属性默认值
 */
@Value("程序新视界")
private String wechatSubscription;

/**
 *  注入操作系统属性
 */
@Value("#{systemProperties['os.name']}")
private String systemPropertiesName;

/**
 * 注入表达式结果
 */
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber;

/**
 * 注入其他Bean属性:注入config对象的属性tool
 */
@Value("#{config.tool}")
private String tool;

/**
 * 注入列表形式(自动根据"|"分割)
 */
@Value("#{'${words}'.split('\\|')}")
private List<String> numList;

/**
 * 注入文件资源
 */
@Value("classpath:config.xml")
private Resource resourceFile;

/**
 * 注入URL资源
 */
@Value("http://www.choupangxia.com")
private URL homePage;

默认值:

/**
 * 如果属性中未配置ip,则使用默认值
 */
@Value("${ip:127.0.0.1}")
private String ip;

/**
 * 如果系统属性中未获取到port的值,则使用8888。
 */
@Value("#{systemProperties['port']?:'8888'}")
private String port;

@Import

1、@Import只能用在类上 ,@Import通过快速导入的方式实现把实例加入spring的IOC容器中

2、加入IOC容器的方式有很多种,@Import注解就相对很牛皮了,@Import注解可以用于导入第三方包 ,当然@Bean注解也可以,但是@Import注解快速导入的方式更加便捷

3、@Import注解有三种用法

三种用法:

//1. 直接填对应的class数组,class数组可以有0到多个。
@Import({ 类名.class , 类名.class... })  


//2. 实现ImportSelector,返回多个  全类名
public class Myclass implements ImportSelector {
//既然是接口肯定要实现这个接口的方法
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[0];
    }
}

//3. 实现ImportBeanDefinitionRegistrar方式,手动注册
public class Myclass2 implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        //指定bean定义信息(包括bean的类型、作用域...)
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(TestDemo4.class);
        //注册一个bean指定bean名字(id)
        beanDefinitionRegistry.registerBeanDefinition("TestDemo4444",rootBeanDefinition);
    }
}

第2、3种方式都需要将实现类,通过@Import加载进来

 详情见:spring注解之@Import注解的三种使用方式 - 宜春 - 博客园

@DependsOn

创建当前bean之前,需要先创建特定bean

@Profile

通过@profile来激活需要的环境

转自:Spring:Spring注解大全 - 怒吼的萝卜 - 博客园

Spring中注解大全和应用_编程无界的博客-CSDN博客_spring 注解大全

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架中,有很多注解可以用来实现依赖注入和组件扫描等功能。以下是一些常用的Spring注解: 1. @Autowired:用于自动装配依赖关系。默认按照byType方式进行bean匹配,可以通过指定name属性或者使用@Qualifier注解来指定bean的名称。 2. @Resource:与@Autowired注解作用相似,但是默认按照byName方式进行bean匹配。可以通过指定name属性或者type属性来指定bean的名称或类型。 3. @Component:用于标注一个普通的Spring组件。可以与@Autowired或@Resource一起使用,实现依赖注入。 4. @Service:用于标注一个服务层组件。通常用于标识业务逻辑的实现类。 5. @Repository:用于标注一个数据访问组件,即DAO组件。通常用于标识数据访问层的实现类。 6. @Controller:用于标注一个控制器组件,通常用于标识处理请求的类。 7. @Configuration:用于标注一个配置类,通常与@Bean注解一起使用,用于定义Spring的配置信息。 8. @Scope:用于指定bean的作用域,包括singleton、prototype、request、session等。 9. @Value:用于注入属性值,可以从配置文件中读取。 以上只是一些常用的Spring注解,还有其他更多的注解可以用于实现不同的功能。使用这些注解可以简化代码,提高开发效率。 #### 引用[.reference_title] - *1* *2* *3* [Spring常用注解详解大全(建议收藏)](https://blog.csdn.net/m0_51538362/article/details/114828582)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值