news 2026/5/4 13:34:35

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/29 23:16:56

【光学】基于遗传算法GA设计最优光学多层滤波器附Matlab代码

✅作者简介&#xff1a;热爱科研的Matlab仿真开发者&#xff0c;擅长数据处理、建模仿真、程序设计、完整代码获取、论文复现及科研仿真。&#x1f34e; 往期回顾关注个人主页&#xff1a;Matlab科研工作室&#x1f34a;个人信条&#xff1a;格物致知,完整Matlab代码获取及仿真…

作者头像 李华
网站建设 2026/5/3 16:33:30

链表中的回文判断

给一个链表&#xff0c;判断这个链表是否为回文链表。能否使用O(1)的空间复杂度解决问题&#xff1f;思路1&#xff1a;使用辅助空间&#xff0c;我们这里给出了使用动态数组作为检查表&#xff0c;给出了两种实现方式&#xff0c;但是这种实现方式效率不高。​ public class L…

作者头像 李华
网站建设 2026/5/1 5:00:26

技术架构的核心目标

技术架构的核心问题与目标 技术架构的核心在于解决系统在物理层面的稳定性、性能和扩展性问题&#xff0c;确保业务功能在复杂环境下可靠运行。以下是技术架构需重点解决的问题及实现目标&#xff1a;系统的物理组成 一个完整的系统由多个层级构成&#xff1a; 接入系统&#x…

作者头像 李华
网站建设 2026/5/4 0:49:13

算法导论第三版,学习日志,2.思考

2-1 &#xff08;在归并排序中对小数组采用插入排序&#xff09;虽然归并排序的最坏情况运行时间为 Θ(n lg n)&#xff0c;而插入排序的最坏情况运行时间为 Θ(n)&#xff0c;但是插入排序中的常量因子可能使得它在 n 较小时&#xff0c;在许多机器上实际运行得更快。因此&…

作者头像 李华
网站建设 2026/5/2 1:55:05

Python数据类型入门

引言 在Python编程中&#xff0c;数据类型就像“食材”&#xff0c;掌握它们才能做出美味的“代码大餐”。今天我们用生活中的例子&#xff0c;带大家认识Python最常用的6种数据类型&#xff0c;看完就能动手写代码&#xff01; 一、整数与浮点数&#xff1a;数字的两种形态 整…

作者头像 李华