Spring-----注解开发和Spring测试单元

一、注解开发

  • 导入jar包;spring-aop-xxx.jar
  • 导入约束:(在官方文档xsd-configuration.html可找)
    <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        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/context http://www.springframework.org/schema/context/spring-context.xsd"> 
  • xml中配置扫描开关:

<context:component-scan base-package="com.itheima"/>

  • 1. ioc注解
/*
 1. @Component组件,表示要托管这个类,让spring创建这个类的实例。 括号里面的us 其实就是id标识符
 
 2. @Component 是通用的注解, 对任何托管的类都可以使用,但是spring为了迎合三层架构,所以对每一层
 也给出了具体的注解。
 
         Action  --- @Controller
         Service --- @Service
         Dao --- @Repository :仓库,
 
     建议: 如果以后托管三层中的类,请使用具体对应的注解,如果托管的是普通的其他类。@Component
 
 3. 默认生成的实例还是单例,如果想做成多例,那么还得添加一个注解
         @Scope("prototype")
 
 4.  @PostConstruct  //初始化实例的时候调用
        @PreDestroy  //销毁实例之前,调用
 
 5. 如果使用注解托管某一个类,不写属性值,那么默认的id标识符就是类的名字(首字母是小写) userServiceImpl
 
 6.<!-- 如果想要扫描多个包,就写一个通用的前缀即可 -->
<context:component-scan base-package="com.itheima"/>
 
*/

DI注解

使用注解来完成依赖注入。 一般注解注入,它针对的点是对象的注入。 spring针对对象的注入,提供了两个注解  @Resource  和  @Autowired

- 常用的注解就两个 @Resource  &  @Autowired

@Resource(name="ud")  根据给定的标记找到对应的类,创建对象,注入进来。

@Autowired  自动装配,会找到对应的实现类创建对象,注入进来。但是如果存在多个实现,那么会抛出异常

二、Spring测试单元

  1. 步骤:导入jar包-->托管业务逻辑类-->在测试类上打上注解 ,给测试类的成员变量注入值
//spring扩展了junit的运行环境,除了有测试功能之外,还在里面定义了创建工厂的代码
@RunWith(SpringJUnit4ClassRunner.class)

//告诉spring的测试环境,配置文件在哪里
@ContextConfiguration("classpath:applicationContext.xml")
public class TestUserService {
    
    //测试类里面出现的注解,不用打开扫描开关。因为这个测试环境里面,它会解析这个测试类的注解。   
    @Autowired
    private UserService userService;
    @Test
    public void testSave(){
        userService.save();
    } 
}
原文地址:https://www.cnblogs.com/sanmaotage/p/8406794.html