Spring注解开发(常用注解的用法)

1.Spring原始注解(刚开始就有)主要代替Bean的配置

注解 说明
@Component 使用在类上用于实例化Bean
@Controller 使用在web层用于实例化Bean
@Service 使用在Service层用于实例化Bean
@Repository 使用在DAO层用于实例化Bean
@Autowired 使用在字段上根据类型依赖注入
@Qualifier 结合@Autowired一起使用根据名称进行依赖注入
@Resource 相当于@Autowired+@Qualifier,安装名称注入
@Value 注入普通属性(配置文件的变量)
@Scope 标注Bean的作用范围
@PostConstruct 使用在方法上标注该方法是Bean的初始化方法
@PreDestroy  使用在方法上标注该方法是Bean的销毁方法

2.Spring新注解(出来的比元注解晚些)可以加载配置文件,第三方Bean类配置操作

注解  说明
@Configuration 用于指定当前类是一个Spring配置类,当创建容器时会从该类上加载
@ComponentScan

用于指定Spring在初始化容器时要扫描的包

作用和在Spring的xml配置文件中

<context:component-scan base-package="com.cc8w"/>一样

@Bean 使用在方法上,标注该方法的返回值会存储到Spring容器中
@PropertySource 用于加载.properties文件的配置
@Import 用于导入其他配置类

3.Spring集成Junit步骤

  1. 导入Spring集成Junit的坐标
  2. 使用@Runwith注解替换原来的运行期
  3. 使用@ContextConfiguration指定配置文件或配置类
  4. 使用@Autowired注入要测的对象
  5. 创建测试类
package com.cc8w.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.cc8w.aop.TargetInterface;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:testApplicationContext.xml"})

public class TestAop {
    @Autowired
    @Qualifier("target") //如果xml配置的几个bean指向同一个class,用这个指定那个bean
    //@Resource相当于@Autowired+@Qualifier
    TargetInterface target; 
    
    @Test
    public void testAopBefore1() {
        target.save();
    }
    

}

二,在每个控制器前面执行 @ModelAttribute

可以把“项目的变了”存到里面 , 参考 https://www.cnblogs.com/cobcmw/p/12092591.html

三,接收参数的注解  @RequestParam

原文地址:https://www.cnblogs.com/fps2tao/p/13331288.html