Spring-注解开发

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: Spring-注解开发

在这里插入图片描述

✨博客主页:👉不会压弯的小飞侠
✨欢迎关注:👉点赞👍收藏⭐留言✒
✨系列专栏:👉spring专栏
✨如果觉得博主的文章还不错的话,请三连支持一下博主。
✨欢迎大佬指正,一起学习!一起加油!

@TOC


一、注解开发定义Bean

1.使用@component定义Bean

package com.test.dao.impl;
import com.test.dao.BookDao;
import org.springframework.stereotype.Component;


@Component("dao")
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("BookDaoImpl...");
    }
}

2.核心配置文件通过组件扫描加载Bean

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
   <context:component-scan base-package="com.test.dao.impl"></context:component-scan>
 
</beans>

3.案例

1.BookDao

package com.test.dao;

public interface BookDao {
    void save();
}

2.BookDaoImpl

package com.test.dao.impl;
import com.test.dao.BookDao;
import org.springframework.stereotype.Component;


@Component("dao")
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("BookDaoImpl...");
    }
}

3.BookService

package com.test.service;

public interface BookService {
    void save();
}

4.BookServiceImpl

package com.test.service.impl;

import com.test.dao.BookDao;
import com.test.service.BookService;
import org.springframework.stereotype.Component;

@Component
public class BookServiceImpl implements BookService {
    private BookDao bookDao;
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    public void save() {
        System.out.println("BookServiceImpl...");
    }
}

5.applicationContext.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
   <context:component-scan base-package="com.test.dao.impl"></context:component-scan>
   <context:component-scan base-package="com.test.service"></context:component-scan>


</beans>

6.Test

import com.test.dao.BookDao;
import com.test.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookDao bookDao = context.getBean("dao",BookDao.class);
        System.out.println(bookDao);
        BookService bean = context.getBean(BookService.class);
        System.out.println(bean);
    }
}
/*
com.test.dao.impl.BookDaoImpl@5427c60c
com.test.service.impl.BookServiceImpl@6366ebe0
 */

二、纯注解开发

1.@Configuration注解代替了Spring的核心配置文件

@Configuration

2.@ComponentScan注解用于设定扫描路径

@ComponentScan("com.test")

3.加载配置类的初始化容器

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

4.案例

1.BookDao

package com.test.dao;

public interface BookDao {
    void save();
}

2.BookDaoImpl

package com.test.dao.impl;
import com.test.dao.BookDao;
import org.springframework.stereotype.Component;


@Component("dao")
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("BookDaoImpl...");
    }
}

3.BookService

package com.test.service;

public interface BookService {
    void save();
}

4.BookServiceImpl

package com.test.service.impl;

import com.test.dao.BookDao;
import com.test.service.BookService;
import org.springframework.stereotype.Component;

@Component
public class BookServiceImpl implements BookService {
    private BookDao bookDao;
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    public void save() {
        System.out.println("BookServiceImpl...");
    }
}

5.SpringConfig

package com.test.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.test")
public class SpringConfig {

}

6.Test

import com.test.config.SpringConfig;
import com.test.dao.BookDao;
import com.test.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookDao bookDao = context.getBean("dao",BookDao.class);
        System.out.println(bookDao);
        BookService bean = context.getBean(BookService.class);
        System.out.println(bean);
    }
}
/*
com.test.dao.impl.BookDaoImpl@77e4c80f
com.test.service.impl.BookServiceImpl@255b53dc
 */

三、Bean的作用范围和生命周期

1.@Scope()定义Bean的作用范围

package com.test.dao.impl;
import com.test.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Scope("singleton")
@Component("dao")
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("BookDaoImpl...");
    }   
}

2.@PostConstruct和@PreDestroy定义Bean的生命周期

package com.test.dao.impl;
import com.test.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Scope("singleton")
@Component("dao")
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("BookDaoImpl...");
    }
    @PostConstruct
    public void init(){
        System.out.println("init...");
    }
    @PreDestroy
    public void destroy(){
        System.out.println("destroy...");
    }
}

四、自动装配

1.使用@Autowired开启自动装配模式

package com.test.service.impl;

import com.test.dao.BookDao;
import com.test.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;
    /*set可以省略*/
    /*public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }*/

    public void save() {
        System.out.println("BookServiceImpl...");
        bookDao.save();
    }
}
  • 注意︰自动装配基于反射设计创建对象并暴力反射对应属性为私有属性初始化数据,因此无需提供setter方法
  • 注意∶自动装配建议使用无参构造方法创建对象(默认),如果不提供对应构造方法,请提供唯一的构造方法

2.使用@Qualifier注解开启指定名称装配Bean

package com.test.service.impl;

import com.test.dao.BookDao;
import com.test.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class BookServiceImpl implements BookService {
    @Autowired
    @Qualifier("dao2")
    private BookDao bookDao;
    /*set可以省略*/
    /*public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }*/

    public void save() {
        System.out.println("BookServiceImpl...");
        bookDao.save();
    }
}

3.使用@Value进行简单的注入

package com.test.dao.impl;
import com.test.dao.BookDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component("dao1")
public class BookDaoImpl implements BookDao {
    @Value("小马哥")
    private String name;
    public void save() {
        System.out.println("BookDaoImpl..."+name);
    }

}

4.使用@PropertySource注解加载properties文件

@PropertySource("jdbc.properties")

5.案例
jdbc.properties

name=Jack

1.BookDao

package com.test.dao;

public interface BookDao {
    void save();
}

2.BookDaoImpl

package com.test.dao.impl;
import com.test.dao.BookDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component("dao1")
public class BookDaoImpl implements BookDao {
    /*@Value("小马哥")*/
    @Value("${name}")
    private String name;
    public void save() {
        System.out.println("BookDaoImpl..."+name);
    }

}

3.BookDaoImpl2

package com.test.dao.impl;
import com.test.dao.BookDao;
import org.springframework.stereotype.Component;


@Component("dao2")
public class BookDaoImpl2 implements BookDao {
    public void save() {
        System.out.println("BookDaoImpl2...");
    }

}

4.BookService

package com.test.service;

public interface BookService {
    void save();
}

5.BookServiceImpl

package com.test.service.impl;

import com.test.dao.BookDao;
import com.test.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class BookServiceImpl implements BookService {
    @Autowired
    @Qualifier("dao1")
    private BookDao bookDao;
    /*set可以省略*/
    /*public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }*/

    public void save() {
        System.out.println("BookServiceImpl...");
        bookDao.save();
    }
}

6.SpringConfig

package com.test.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ComponentScan("com.test")
@PropertySource("jdbc.properties")
public class SpringConfig {

}

7.Test

import com.test.config.SpringConfig;
import com.test.dao.BookDao;
import com.test.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookService dao = context.getBean(BookService.class);
        dao.save();
    }
}
/*
BookServiceImpl...
BookDaoImpl...Jack

 */

五、第三方Bean管理

1.使用@Bean配置第三方bean

SpringConfig:

package com.jkj.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class SpringConfig {
    //2.添加@Bean,表示当前方法的返回值是一个bean
    @Bean
    //1.定义一个方法获得要管理的对象
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/spring");
        ds.setUsername("root");
        ds.setPassword("root");
        return ds;
    }

}

Test:

import com.jkj.config.SpringConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.sql.DataSource;

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        DataSource bean = context.getBean(DataSource.class);
        System.out.println(bean);
    }
}

2.将独立的配置类加入核心配置

1.导入式
使用@Import注解手动加入配置类到核心配置,此注解只能添加一次,多个数据使用数组格式。

案例:
SpringConfig:

package com.jkj.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import javax.sql.DataSource;

@Configuration
@Import(JdbcConfig.class)
public class SpringConfig {
}

JdbcConfig:

package com.jkj.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class JdbcConfig {
    //2.添加@Bean,表示当前方法的返回值是一个bean
    @Bean
    //1.定义一个方法获得要管理的对象
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/spring");
        ds.setUsername("root");
        ds.setPassword("root");
        return ds;
    }
}

2.扫描式(不推荐使用)
使用@ComponentScan注解扫描配置类所在的包,加载对应的配置类信息

案例:
SpringConfig:

package com.jkj.config;

        import com.alibaba.druid.pool.DruidDataSource;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.ComponentScan;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.context.annotation.Import;

        import javax.sql.DataSource;

@Configuration
@ComponentScan("com.jkj.config")
public class SpringConfig {


}

JdbcConfig:

package com.jkj.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
@Configuration
public class JdbcConfig {
    //2.添加@Bean,表示当前方法的返回值是一个bean
    @Bean
    //1.定义一个方法获得要管理的对象
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/spring");
        ds.setUsername("root");
        ds.setPassword("root");
        return ds;
    }
}

六、第三方Bean依赖注入

1.简单依赖注入

public class JdbcConfig {
    @Value("com.mysql.jdbc.Driver")
    private String driver;
    @Value("jdbc:mysql://localhost:3306/spring")
    private String url;
    @Value("root")
    private String username;
    @Value("root")
    private String password;
    
    //2.添加@Bean,表示当前方法的返回值是一个bean
    @Bean
    //1.定义一个方法获得要管理的对象
    public DataSource dataSource(){
        System.out.println(bookDao);
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

2.引用类型注入

引用类型注入只需要bean定义方法设置形参即可,容器会根据类型自动装配对象。

   //2.添加@Bean,表示当前方法的返回值是一个bean
    @Bean
    //1.定义一个方法获得要管理的对象
    public DataSource dataSource(BookDao bookDao){
        System.out.println(bookDao);
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

七、xml配置比对注解配置

  • 定义bean

    • xml配置:bean标签:id属性,class属性
    • 注解:@Component,@controller,@Service,@Repository,@ComponentScan
  • 设置依赖注入

    • xml配置:setter注入(set方法),构造器注入(构造方法),引用/简单,自动装配
    • 注解:@Autowired,@Qualifier,@Value
  • 配置第三方bean

    • xml配置:bean标签:静态工厂、实例工厂、FactoryBean
    • 注解:@Bean
  • 作用范围

    • xml配置:scope属性
    • 注解:@scope
  • 生命周期

    • xml配置:标准接口,init-method,destroy-method
    • 注解:@PostConstructor,@PreDestroy
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
11天前
|
缓存 监控 Java
SpringBoot @Scheduled 注解详解
使用`@Scheduled`注解实现方法周期性执行,支持固定间隔、延迟或Cron表达式触发,基于Spring Task,适用于日志清理、数据同步等定时任务场景。需启用`@EnableScheduling`,注意线程阻塞与分布式重复问题,推荐结合`@Async`异步处理,提升任务调度效率。
268 127
|
27天前
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
271 0
|
1月前
|
Java 测试技术 API
将 Spring 的 @Embedded 和 @Embeddable 注解与 JPA 结合使用的指南
Spring的@Embedded和@Embeddable注解简化了JPA中复杂对象的管理,允许将对象直接嵌入实体,减少冗余表与连接操作,提升数据库设计效率。本文详解其用法、优势及适用场景。
214 126
|
2月前
|
XML JSON Java
Spring框架中常见注解的使用规则与最佳实践
本文介绍了Spring框架中常见注解的使用规则与最佳实践,重点对比了URL参数与表单参数的区别,并详细说明了@RequestParam、@PathVariable、@RequestBody等注解的应用场景。同时通过表格和案例分析,帮助开发者正确选择参数绑定方式,避免常见误区,提升代码的可读性与安全性。
|
13天前
|
XML Java 数据格式
常用SpringBoot注解汇总与用法说明
这些注解的使用和组合是Spring Boot快速开发和微服务实现的基础,通过它们,可以有效地指导Spring容器进行类发现、自动装配、配置、代理和管理等核心功能。开发者应当根据项目实际需求,运用这些注解来优化代码结构和服务逻辑。
111 12
|
26天前
|
Java 测试技术 数据库
使用Spring的@Retryable注解进行自动重试
在现代软件开发中,容错性和弹性至关重要。Spring框架提供的`@Retryable`注解为处理瞬时故障提供了一种声明式、可配置的重试机制,使开发者能够以简洁的方式增强应用的自我恢复能力。本文深入解析了`@Retryable`的使用方法及其参数配置,并结合`@Recover`实现失败回退策略,帮助构建更健壮、可靠的应用程序。
106 1
使用Spring的@Retryable注解进行自动重试
|
26天前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
探索Spring Boot的@Conditional注解的上下文配置
|
26天前
|
智能设计 Java 测试技术
Spring中最大化@Lazy注解,实现资源高效利用
本文深入探讨了 Spring 框架中的 `@Lazy` 注解,介绍了其在资源管理和性能优化中的作用。通过延迟初始化 Bean,`@Lazy` 可显著提升应用启动速度,合理利用系统资源,并增强对 Bean 生命周期的控制。文章还分析了 `@Lazy` 的工作机制、使用场景、最佳实践以及常见陷阱与解决方案,帮助开发者更高效地构建可扩展、高性能的 Spring 应用程序。
Spring中最大化@Lazy注解,实现资源高效利用