• Spring-注解开发


    目录

    注解开发的意义

    常用注解-1

    实例演示

    常用注解-2

    实例演示

    常用注解-3

    实例演示

    常用注解-4

    实例演示

    常用注解-5

    实例演示

    常用注解-6

    实例演示

    常用注解-7

    实例演示


    • 注解开发的意义

    • 什么是注解驱动
    • 注解启动时使用注解的形式替代xml配置
    • 将繁杂的spring配置文件从工程中彻底消除掉,简化书写
    • 注解驱动的弊端
    • 为了达成注解驱动的目的,可能会将原先很简单的书写,变的更加复杂
    • XML中配置第三方开发的资源是很方便的
    • 但使用注解驱动无法在第三方开发的资源中进行编辑,因此会增大开发工作量
    • 常用注解-1

    • 启动注解功能
    • 启动注解扫描,加载类中配置的注解项
    • 说明:
    • 在进行包所扫描时,会对配置的包及其子包中所有文件进行扫描
    • 扫描过程是以文件夹递归迭代的形式进行的
    • 扫描过程仅读取合法的java文件
    • 扫描时仅读取spring可识别的注解
    • 扫描结束后会将可识别的有效注解转化为spring对应的资源加入IOC容器
    • 注意:
    • 无论是注解格式还是XML配置格式
    • 最终都是将资源加载到IOC容器中,差别仅仅是数据读取方式不同
    • 从加载效率上来说注解优于XML配置文件
    • bean的定义
    • 名称:@Component @Controller @Service @Repository
    • 类型:类注解
    • 位置:类定义上方
    • 作用:设置该类为spring管理的bean
    • 范例:
    • @Component
    • public class ClassName{}
    • 说明:
    • @Controller @Service @Repository是@Component 的衍生注解,功能同@Component
    • 相关属性:
    • value(默认):定义bean的访问id
    • bean的作用域
    • 名称:@Scope
    • 类型:类注解
    • 位置:类定义上方
    • 作用:设置该类作为bean对应的scope属性
    • 范例:
    • @Scope
    • public class ClassName{}
    • 相关属性:
    • value(默认):定义bean的作用域,默认为singleton
    • bean的生命周期
    • 名称:@PostConstruct @PreDestroy
    • 类型:方法注解
    • 位置:方法定义上方
    • 作用:设置该类作为bean对应的生命周期方法
    • 范例:
    • @PostConstruct
    • public void init() {}
    • 实例演示

    • 准备(各接口及其实现类)
    • dao层
    • service层
    • 配置文件,来个xml先测试下,成功
    • 注解实现
    • 作用域与生命周期简单演示一下,具体效果请移步历史文章
      1. package com.superdemo.service.impl;
      2. import com.superdemo.service.UserService;
      3. import org.springframework.context.annotation.Scope;
      4. import org.springframework.stereotype.Component;
      5. import javax.annotation.PostConstruct;
      6. import javax.annotation.PreDestroy;
      7. //定义bean,后面添加bean的id
      8. @Component("userService")
      9. //设定bean的作用域
      10. @Scope
      11. public class UserServiceImpl implements UserService {
      12. public void save(){
      13. System.out.println("user service running...");
      14. }
      15. //设定bean的生命周期
      16. @PostConstruct
      17. public void init(){
      18. System.out.println("user service init");
      19. }
      20. //设定bean的生命周期
      21. @PreDestroy
      22. public void destroy(){
      23. System.out.println("user service destroy");
      24. }
      25. }
      1. package com.superdemo;
      2. import com.superdemo.dao.BookDao;
      3. import com.superdemo.dao.UserDao;
      4. import com.superdemo.service.UserService;
      5. import org.springframework.context.ApplicationContext;
      6. import org.springframework.context.support.ClassPathXmlApplicationContext;
      7. public class App {
      8. public static void main(String[] args) {
      9. ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
      10. UserService userService = (UserService) ctx.getBean("userService");
      11. userService.save();
      12. UserDao userDao = (UserDao) ctx.getBean("userDao");
      13. userDao.save();
      14. BookDao bookDao = (BookDao) ctx.getBean("bookDao");
      15. bookDao.save();
      16. }
      17. }
    • 常用注解-2

    • 加载第三方资源
    • 名称:@Bean
    • 类型: 方法注解
    • 位置:方法定义上方
    • 作用:设置该方法的返回值作为spring管理的bean
    • 范例:
    • @Bean("dataSource")
    • public DruidDataSource createDataSource(){ return....;}
    • 说明:
    • 因为第三方bean无法在其源码上进行修改,使用@Bean 解决第三方bean的引入问题
    • 该注解用于替代XML配置中的静态工厂与实例工厂创建bean,不区分方法是否为静态或非静态
    • @Bean 所在的类必须被spring扫描加载,否则该注解无法生效
    • 相关属性:
    • value(默认):定义bean的访问id
    • 实例演示

    • 加个数据源Druid
      1. <dependency>
      2. <groupId>com.alibabagroupId>
      3. <artifactId>druidartifactId>
      4. <version>1.2.11version>
      5. dependency>
    • 创建一个类,专门加载第三方bean
      1. package com.superdemo.config;
      2. import com.alibaba.druid.pool.DruidDataSource;
      3. import org.springframework.context.annotation.Bean;
      4. import org.springframework.stereotype.Component;
      5. //为能被spring扫描加载到,后面有替代方案,这里简单用Component写下
      6. @Component
      7. public class JDBCConfig {
      8. @Bean("dataSource")
      9. public DruidDataSource getDataSource(){
      10. DruidDataSource ds = new DruidDataSource();
      11. ds.setDriverClassName("com.mysql.jdbc.Driver");
      12. ds.setUrl("jdbc:mysql://localhost:3306/dp1?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false");
      13. ds.setName("root");
      14. ds.setPassword("123456");
      15. return ds;
      16. }
      17. }
    • 测试成功
      1. DruidDataSource dataSource = (DruidDataSource) ctx.getBean("dataSource");
      2. System.out.println(dataSource);
    • 常用注解-3

    • bean的非引用类型属性注入
    • 名称:@Value
    • 类型:属性注解、方法注解
    • 位置:属性定义上方,方法定义上方
    • 作用:设置对应属性的值或对方法进行传参
    • 范例:
    • @Value("${jdbc.username}")
    • private String username;
    • 说明:
    • value值仅支持非引用类型数据,赋值时对方法的所有参数全部赋值
    • value值支持读取properties文件中的属性值,通过类属性将properties中数据传入类中
    • value值支持SpEL
    • @Value 注解如果添加在属性上方,可以省略set方法(set方法的目的是为属性赋值)
    • 相关属性:
    • value(默认):定义对应的属性值或参数值
    • bean的引用类型属性注入
    • 名称:@Autowired、@Qualifier
    • 类型:属性注解,方法注解
    • 位置:属性定义上方,方法定义上方
    • 作用:设置对应属性的对象或对方法进行引用类型传参
    • 范例:
    • @Autowired(required=false)
    • @Qualifier("userDao")
    • private UserDao userDao;
    • 说明:
    • @Autowired 默认按类型装配
    • 类型相同时会根据所创建名称识别
    • 找不到对应名称就报错
    • 指定@Qualifier 后可以指定自动装配的bean的id(要搭配@Autowired,否则会出现null报错)
    • 相关属性:
    • required:定义该属性是否允许为null
    • 可以使用@Primary 设置类对应的bean按类型装配时优先装配
    • 实例演示

    • 非引用
      1. @Value("3")
      2. private int num;
      3. @Value("icpc")
      4. private String version;
    • 引用
      1. @Autowired
      2. private UserDao userDao2;
      3. @Autowired
      4. @Qualifier("bookDao2")
      5. private BookDao bookDao;
    • 常用注解-4

    • 加载properties文件
    • 名称:@PropertySource
    • 类型:类注解
    • 位置:类定义上方
    • 作用:加载properties文件中的属性值
    • 范例:
    • @PropertySource (value="classpath:filename.properties")
    • public class ClassName {
    • @Value("${propertiesAttributeName}")
    • private String attributeName;
    • }
    • 说明:
    • 不支持*通配格式,一旦加载,所有spring控制的bean中均可使用对应属性值
    • 相关属性:
    • value(默认):设置加载的properties文件名
    • ignoreResourceNotFound:如果资源未找到,是否忽略,默认为false
    • 实例演示

      1. package com.superdemo.service.impl;
      2. import com.superdemo.dao.BookDao;
      3. import com.superdemo.dao.UserDao;
      4. import com.superdemo.service.UserService;
      5. import org.springframework.beans.factory.annotation.Autowired;
      6. import org.springframework.beans.factory.annotation.Qualifier;
      7. import org.springframework.beans.factory.annotation.Value;
      8. import org.springframework.context.annotation.PropertySource;
      9. import org.springframework.context.annotation.Scope;
      10. import org.springframework.stereotype.Component;
      11. import javax.annotation.PostConstruct;
      12. import javax.annotation.PreDestroy;
      13. //定义bean,后面添加bean的id
      14. @Component("userService")
      15. //设定bean的作用域
      16. @Scope
      17. @PropertySource("classpath:jdbc.properties")
      18. public class UserServiceImpl implements UserService {
      19. @Value("3")
      20. private int num;
      21. @Value("icpc")
      22. private String version;
      23. @Autowired
      24. private UserDao userDao2;
      25. @Autowired
      26. @Qualifier("bookDao2")
      27. private BookDao bookDao;
      28. @Value("${jdbc.userName}")
      29. private String userName;
      30. @Value("${jdbc.password}")
      31. private String password;
      32. public void save(){
      33. System.out.println("user service running..."+num+" "+version);
      34. System.out.println("properties: "+userName+" "+password);
      35. userDao2.save();
      36. bookDao.save();
      37. }
      38. //设定bean的生命周期
      39. @PostConstruct
      40. public void init(){
      41. System.out.println("user service init");
      42. }
      43. //设定bean的生命周期
      44. @PreDestroy
      45. public void destroy(){
      46. System.out.println("user service destroy");
      47. }
      48. }
    • 常用注解-5

    • 纯注解格式
    • 名称:@Configuration,@ComponentScan
    • 类型:类注解
    • 位置:类定义上方
    • 作用:设置当前类为spring核心配置加载类
    • 范例
    • @Configuration
    • @ComponentScan("scanPackageName")
    • public class SpringConfigClassName{}
    • 说明:
    • 核心配置类用于替换spring核心配置文件,此类可以设置空的,不设置变量与属性
    • bean扫描工作使用注解@ComponentScan 替代
    • 加载纯注解格式上下文对象,需要使用AnnotationConfigApplicationContext
    • 实例演示

      1. package com.superdemo.config;
      2. import org.springframework.context.annotation.ComponentScan;
      3. import org.springframework.context.annotation.Configuration;
      4. @Configuration
      5. @ComponentScan("com.superdemo")
      6. public class SpringConfig {
      7. }
      1. public class App {
      2. public static void main(String[] args) {
      3. //ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
      4. ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
      5. UserService userService = (UserService) ctx.getBean("userService");
      6. userService.save();
      7. /*UserDao userDao = (UserDao) ctx.getBean("userDao");
      8. userDao.save();*/
      9. /*BookDao bookDao = (BookDao) ctx.getBean("bookDao");
      10. bookDao.save();*/
      11. /*DruidDataSource dataSource = (DruidDataSource) ctx.getBean("dataSource");
      12. System.out.println(dataSource);*/
      13. }
      14. }
    • 常用注解-6

    • 第三方bean配置与管理
    • 名称:@Import
    • 类型:类注解
    • 位置:类定义上方
    • 作用:
    • 导入第三方bean作为spring控制的资源
    • 范例:
    • @Configuration
    • @Import(OtherClassName.class)
    • public class ClassName{}
    • 说明:
    • @Import 注解在同一个类上,仅允许添加一次,如果需要导入多个,使用数组的形式进行设定
    • 在被导入的类中可以继续使用@Import 导入其他资源(了解)
    • @Bean 所在的类可以使用导入的形式进入spring容器,无需声明为bean
    • 很好的解决了之前常用注解-2里为扫描加载到的权宜之计
    • 实例演示

    • 常用注解-7

    • 依赖加载
    • 名称:@DependsOn
    • 类型:类注解,方法注解
    • 位置:bean定义的位置(类上或方法上)
    • 作用:控制bean的加载顺序,使其在指定bean加载完毕后再加载
    • 范例:
    • @DependsOn("beanId")
    • public class ClassName{}
    • 说明:
    • 配置在方法上,使@DependsOn 指定的bean优先于@Bean 配置的bean进行加载
    • 配置在类上,使@DependsOn 指定的bean优先于当前类中所有@Bean 配置的bean进行加载
    • 配置在类上,使@DependsOn 指定的bean优先于@Component 等配置的bean进行加载
    • 相关属性:
    • value(默认):设置当前bean所依赖的bean的id
    • 名称:@Order
    • 类型:配置类注解
    • 位置:配置类定义的位置(类上)
    • 作用:控制配置类的加载顺序
    • 范例
    • @Order (1)
    • public class SpringConfigClassName{}
    • @Lazy 控制bean的加载时机,使其延迟加载,了解一下就行
    • 实例演示

    • 首先测试下看dao和service谁先加载(利用构造)
    • 更改加载顺序
    • 关于@Order
  • 相关阅读:
    [附源码]java毕业设计闲置物品线上交易系统
    初识Hadoop两大核心:HDFS和MapReduce
    Java 并发编程解析 | 每个Java Developer都应该知道的关于并发编程的那点事?
    Mariadb: error Relay log read failure: Could not parse relay log event entry
    【无标题】
    学习笔记11月27日
    MATLAB科学计算从入门到精通
    我常用的两个翻译神器,程序员必备.
    Python笔记——linux/ubuntu下安装mamba,安装bob.learn库
    竞赛 题目:基于卷积神经网络的手写字符识别 - 深度学习
  • 原文地址:https://blog.csdn.net/weixin_59624686/article/details/126729118