首页 > 其他分享 >spring入门aop和ioc基于注解

spring入门aop和ioc基于注解

时间:2024-06-06 10:55:12浏览次数:15  
标签:xml Autowired spring 使用 bean aop 注解 ioc class

目录
请先观看链接

用注解代替xml文件中的部分配置

在要注册bean的地方添加注解

@Component()
不指定名字就是类名的首字母小写
@Component("name")
bean的名字就是括号中指定的值

在注册完以后要开始注册扫描

    <!--    重点是开启注解扫描-->
    <context:component-scan base-package="com.qc.service"/>

bean管理汇总四个常用的注解:

  1. @Component 普通类
  2. @Controller 表现层的类
  3. @Service 业务层的类
  4. @Repository 持久层的类

依赖注入相关的注解

  1. @Value 用于注入简单类型(基本类型+字符串)
  2. @Autowired 默认按类型进行自动装配(自定义引用类型)
  3. @Qualifier 不能单独使用,必须要和@Autowired一起使用,强制使用名称注入,即:就是对于@Autowired指定使用
  4. @Resource java提供的注解,也可以达到强制使用名称注入的作用,此注解是单独使用的,但是在使用时注意使用name属性制定名称

对象生命周期相关的注解

  1. @Scope 取值singleton(单例)prototype(多例)

初始化方法和销毁方法注解(了解部分)

  1. @PostConstruct 相当于init-method 该注解作用到方法上
  2. @PreDestroy 相当于destroy-method 该注解也是作用到方法上

ioc纯注解开发

// 声明当前的类是配置类
@Configuration
// 扫描指定的包路径
@ComponentScan("com.qc")
public class SpringConfig {

}

在测试类中:

// 创建工厂
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
Car car = (Car) ac.getBean("car");
System.out.println(car);

spring整合junit简化测试开发

@RunWith(SpringJUnit4ClassRunner.class)
// 配置文件
@ContextConfiguration(locations = "classpath:applicationContext.xml")
// 配置类
@ContextConfiguration(classes = SpringConfig.class)
// 在测试类中添加这两个注解,可以将要使用的对象通过@Autowired注入

标签:xml,Autowired,spring,使用,bean,aop,注解,ioc,class
From: https://www.cnblogs.com/ning23/p/18234702

相关文章