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...");
    }
}
AI 代码解读

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>
AI 代码解读

3.案例

1.BookDao

package com.test.dao;

public interface BookDao {
    void save();
}
AI 代码解读

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...");
    }
}
AI 代码解读

3.BookService

package com.test.service;

public interface BookService {
    void save();
}
AI 代码解读

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...");
    }
}
AI 代码解读

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>
AI 代码解读

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
 */
AI 代码解读

二、纯注解开发

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

@Configuration
AI 代码解读

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

@ComponentScan("com.test")
AI 代码解读

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

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
AI 代码解读

4.案例

1.BookDao

package com.test.dao;

public interface BookDao {
    void save();
}
AI 代码解读

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...");
    }
}
AI 代码解读

3.BookService

package com.test.service;

public interface BookService {
    void save();
}
AI 代码解读

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...");
    }
}
AI 代码解读

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 {

}
AI 代码解读

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
 */
AI 代码解读

三、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...");
    }   
}
AI 代码解读

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...");
    }
}
AI 代码解读

四、自动装配

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();
    }
}
AI 代码解读
  • 注意︰自动装配基于反射设计创建对象并暴力反射对应属性为私有属性初始化数据,因此无需提供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();
    }
}
AI 代码解读

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);
    }

}
AI 代码解读

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

@PropertySource("jdbc.properties")
AI 代码解读

5.案例
jdbc.properties

name=Jack
AI 代码解读

1.BookDao

package com.test.dao;

public interface BookDao {
    void save();
}
AI 代码解读

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);
    }

}
AI 代码解读

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...");
    }

}
AI 代码解读

4.BookService

package com.test.service;

public interface BookService {
    void save();
}
AI 代码解读

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();
    }
}
AI 代码解读

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 {

}
AI 代码解读

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

 */
AI 代码解读

五、第三方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;
    }

}
AI 代码解读

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);
    }
}
AI 代码解读

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 {
}
AI 代码解读

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;
    }
}
AI 代码解读

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 {


}
AI 代码解读

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;
    }
}
AI 代码解读

六、第三方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;
    }
AI 代码解读

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;
    }
AI 代码解读

七、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
相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
飞算 JavaAI:革新电商订单系统 Spring Boot 微服务开发
在电商订单系统开发中,传统方式耗时约30天,需应对复杂代码、调试与测试。飞算JavaAI作为一款AI代码生成工具,专注于简化Spring Boot微服务开发。它能根据业务需求自动生成RESTful API、数据库交互及事务管理代码,将开发时间缩短至1小时,效率提升80%。通过减少样板代码编写,提供规范且准确的代码,飞算JavaAI显著降低了开发成本,为软件开发带来革新动力。
从基础到进阶:Spring Boot + Thymeleaf 整合开发中的常见坑与界面优化
本文深入探讨了 **Spring Boot + Thymeleaf** 开发中常见的参数绑定问题与界面优化技巧。从基础的 Spring MVC 请求参数绑定机制出发,分析了 `MissingServletRequestParameterException` 的成因及解决方法,例如确保前后端参数名、类型一致,正确设置请求方式(GET/POST)。同时,通过实际案例展示了如何优化支付页面的视觉效果,借助简单的 CSS 样式提升用户体验。最后,提供了官方文档等学习资源,帮助开发者更高效地掌握相关技能。无论是初学者还是进阶用户,都能从中受益,轻松应对项目开发中的挑战。
114 0
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
356 26
Java 21 与 Spring Boot 3.2 微服务开发从入门到精通实操指南
《Java 21与Spring Boot 3.2微服务开发实践》摘要: 本文基于Java 21和Spring Boot 3.2最新特性,通过完整代码示例展示了微服务开发全流程。主要内容包括:1) 使用Spring Initializr初始化项目,集成Web、JPA、H2等组件;2) 配置虚拟线程支持高并发;3) 采用记录类优化DTO设计;4) 实现JPA Repository与Stream API数据访问;5) 服务层整合虚拟线程异步处理和结构化并发;6) 构建RESTful API并使用Springdoc生成文档。文中特别演示了虚拟线程配置(@Async)和StructuredTaskSco
85 0
Java 开发玩转 MCP:从 Claude 自动化到 Spring AI Alibaba 生态整合
本文详细讲解了Java开发者如何基于Spring AI Alibaba框架玩转MCP(Model Context Protocol),涵盖基础概念、快速体验、服务发布与调用等内容。重点包括将Spring应用发布为MCP Server(支持stdio与SSE模式)、开发MCP Client调用服务,以及在Spring AI Alibaba的OpenManus中使用MCP增强工具能力。通过实际示例,如天气查询与百度地图路线规划,展示了MCP在AI应用中的强大作用。最后总结了MCP对AI开发的意义及其在Spring AI中的实现价值。
1132 9
SpringBoot缓存注解使用
Spring Boot 提供了一套方便的缓存注解,用于简化缓存管理。通过 `@Cacheable`、`@CachePut`、`@CacheEvict` 和 `@Caching` 等注解,开发者可以轻松地实现方法级别的缓存操作,从而提升应用的性能和响应速度。合理使用这些注解可以大大减少数据库的访问频率,优化系统性能。
280 89
Spring MVC常用的注解
@RequestMapping:用于处理请求 url 映射的注解,可用于类或方法上。用于类上,则表示类中 的所有响应请求的方法都是以该地址作为父路径。 @RequestBody:注解实现接收http请求的json数据,将json转换为java对象。 @ResponseBody:注解实现将conreoller方法返回对象转化为json对象响应给客户。 @Controller:控制器的注解,表示是表现层,不能用用别的注解代替 @RestController : 组合注解 @Conntroller + @ResponseBody @GetMapping , @PostMapping , @Put
Spring Boot的核心注解是哪个?他由哪几个注解组成的?
Spring Boot的核心注解是@SpringBootApplication , 他由几个注解组成 : ● @SpringBootConfiguration: 组合了- @Configuration注解,实现配置文件的功能; ● @EnableAutoConfiguration:打开自动配置的功能,也可以关闭某个自动配置的选项 ● @ComponentScan:Spring组件扫描

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等