news 2026/4/18 8:34:41

SpringIOC的注解开发

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
SpringIOC的注解开发

目录

1.快速入门

2.常用注解

bean管理类常用的4个注解(作用相同,推荐使用在不同分层上) ​

依赖注入常用的注解

对象生命周期(作用范围)注解

3.纯注解模式


1.快速入门

导入依赖:

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> </dependencies>

在配置文件中开启注解扫描:

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描 --> <context:component-scan base-package="com.qcby"/> </beans>

创建接口和实现类:

package com.qcby.service; public interface UserService { public void hello(); } package com.qcby.service.Impl; import com.qcby.service.UserService; import org.springframework.stereotype.Component; /** * @Component 作用是把当前类使用IOC容器进行管理,如果没有指定名称,默认使用当前类名userServiceImpl */ @Component(value = "userService") public class UserServiceImpl implements UserService { @Override public void hello() { System.out.println("hello IOC注解........"); } }

测试代码:

import com.qcby.service.UserService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Demo { @Test public void test1() { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = (UserService) context.getBean("userService"); userService.hello(); } }

运行结果:

我们在实现类上面加了@Component注解,它的作用是把当前类使用IOC容器进行管理,value指定Bean的名称,如果没有指定名称,默认使用当前类名userServiceImpl

2.常用注解

bean管理类常用的4个注解(作用相同,推荐使用在不同分层上) ​

@Component普通的类

@Controller表现层

@Service业务层

@Repository持久层

依赖注入常用的注解

@Value用于注入普通类型(String,int,double等类型) ​

@Autowired默认按类型进行自动装配(引用类型) ​

@Qualifier和@Autowired一起使用,强制使用名称注入 ​

@Resource JavaEE提供的注解,也被支持。使用name属性,按名称注入

对象生命周期(作用范围)注解

@Scope生命周期注解,取值singleton(默认值,单实例)和prototype(多例)

初始化方法和销毁方法注解

@PostConstruct相当于init-method

@PreDestroy相当于destroy-method

3.纯注解模式

纯注解的方式是微服务架构开发的主要方式,所以也是非常的重要。纯注解的目 的是替换掉所有的配置文件。但是需要编写配置类。

配置类:

package com.qcby.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * spring的配置类,替换掉applicationContext.xml */ //声明这个类是配置类 @Configuration //扫描指定的包结构 @ComponentScan(value="com.qcby") public class SpringConfig { }

实体类:

package com.qcby.entity; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class Order { @Value("北京") private String address; @Override public String toString() { return "Order [address=" + address + "]"; } }

测试方法:

import com.qcby.config.SpringConfig; import com.qcby.entity.Order; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Demo { /** * 需要加载配置类 */ @Test public void test() { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); //获取对象 Order order = (Order) context.getBean("order"); System.out.println(order); } }

@Configuration声明是配置类

@ComponentScan扫描具体包结构的

@Import注解Spring的配置文件可以分成多个配置的,编写多个配置类。用于导入其他配置类

@Bean注解只能写在方法上,表明使用此方法创建一个对象,对象创建完成保 存到IOC容器中

创建SpringConfig2,在SpringConfig2当中配置德鲁伊连接池:

package com.qcby.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.context.annotation.Bean; import javax.sql.DataSource; public class SpringConfig2 { @Bean(name = "dataSource") public DataSource createDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/spring_db"); dataSource.setUsername("root"); dataSource.setPassword("root"); return dataSource; } }

在原来的配置类当中导入配置:

package com.qcby.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** * spring的配置类,替换掉applicationContext.xml */ //声明这个类是配置类 @Configuration //扫描指定的包结构 @ComponentScan(value="com.qcby") @Import(value={SpringConfig2.class}) public class SpringConfig { }

创建实体类:

package com.qcby.entity; public class Account { private int id; private String name; private Double money; public Account(String name, int id, Double money) { this.name = name; this.id = id; this.money = money; } public Account() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } @Override public String toString() { return "Account [id=" + id + ", name=" + name + ", money=" + money + "]"; } }

持久层:

package com.qcby.dao; import com.qcby.entity.Account; import java.util.List; public interface AccountDao { List<Account> findAll(); } package com.qcby.dao.Impl; import com.qcby.dao.AccountDao; import com.qcby.entity.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; @Repository public class AccountDaoImpl implements AccountDao { @Autowired private DataSource dataSource; @Override public List<Account> findAll() { List<Account> list = new ArrayList<>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try{ //获取连接 conn=dataSource.getConnection(); //编写sql String sql="select * from account"; //预编译 ps=conn.prepareStatement(sql); //查询 rs= ps.executeQuery(); while(rs.next()){ Account account=new Account(); account.setId(rs.getInt("id")); account.setName(rs.getString("name")); account.setMoney(rs.getDouble("money")); list.add(account); } } catch (Exception e) { throw new RuntimeException(e); }finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } return list; } }

业务层:

package com.qcby.service.Impl; import com.qcby.dao.AccountDao; import com.qcby.entity.Account; import com.qcby.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; @Override public List<Account> findAll() { return accountDao.findAll(); } } package com.qcby.service; import com.qcby.entity.Account; import java.util.List; public interface AccountService { List<Account> findAll(); }

测试代码:

@Test public void test2() { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); AccountService accountService = context.getBean(AccountService.class); List<Account> list=accountService.findAll(); for(Account account:list){ System.out.println(account); } }

结果:

可见我们在配置类2当中的配置也生效了

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/18 3:26:07

python训练营打卡day11

浙大疏锦行 知识点&#xff1a; 1.网格搜索 2.随机搜索 3.贝叶斯优化 4.time库的记时模块 5.代理模型的思想 6.给ai提问 1. 概述 核心知识点回顾 模型组成 算法 实例化设置的外参&#xff08;超参数&#xff09; 训练得到的内参 调参原则&#xff1a;只要调参就需要…

作者头像 李华
网站建设 2026/4/18 3:26:55

关于链表中元素的交换的操作

给定一个链表&#xff0c;对于每两个相邻的结点&#xff0c;交换其位置。如 1->2->3->4->null&#xff0c;返回2->1->3->4->null只能对结点进行操作&#xff0c;不能修改结点的值&#xff0c;只能操作结点&#xff08;整个&#xff09;或结点对应的指针…

作者头像 李华
网站建设 2026/4/18 3:25:37

【大模型预训练】07-数据处理流程设计:从原始数据到模型输入的端到端处理链路

引言数据处理流程设计是现代数据科学和机器学习领域中不可或缺的一环。它涵盖了从原始数据采集到最终模型输入的整个端到端处理链路&#xff0c;确保数据在各个阶段得到有效管理和转换&#xff0c;从而为后续的分析和建模提供高质量的数据基础。在数据驱动的决策日益重要的今天…

作者头像 李华
网站建设 2026/4/17 20:35:18

2025软件测试面试题及答案

【纯干货&#xff01;&#xff01;&#xff01;】花费了整整3天&#xff0c;整理出来的全网最实用软件测试面试大全&#xff0c;一共30道题目答案的纯干货&#xff0c;希望大家多多支持&#xff0c;建议 点赞&#xff01;&#xff01;收藏&#xff01;&#xff01;长文警告&…

作者头像 李华
网站建设 2026/4/18 4:26:49

AI中的优化5-无约束非线性规划之凸性

目录 正文 一、核心概念 1. 全局最小、局部最小、严格局部最小 2. 梯度 &#xff08;1&#xff09;矩阵的偏导数计算&#xff08;梯度&#xff09; &#xff08;2&#xff09;Hessian Matrix &#xff08;3&#xff09;方向导数与梯度 &#xff08;4&#xff09;可行方…

作者头像 李华