新商盟显示 检查网站开发错误呢,进入公众号主页,选择锦州网站建设,湖南网站建设公司 尖端磐石网络IOC的配置文件开发方式
这里我们编写业务层和持久层代码进行演示#xff0c;抛去表现层实现 Spring 框架开发
技术选择#xff1a;创建 maven Java 工程#xff0c;导入坐标依赖#xff0c;在这里我们持久层选择使用原始的 JDBC 程序#xff0c;连接池选择 Druid 连接池…IOC的配置文件开发方式这里我们编写业务层和持久层代码进行演示抛去表现层实现 Spring 框架开发技术选择创建 maven Java 工程导入坐标依赖在这里我们持久层选择使用原始的 JDBC 程序连接池选择 Druid 连接池dependencies dependency groupIdorg.springframework/groupId artifactIdspring-context/artifactId version5.0.2.RELEASE/version /dependency dependency groupIdcommons-logging/groupId artifactIdcommons-logging/artifactId version1.2/version /dependency dependency groupIdlog4j/groupId artifactIdlog4j/artifactId version1.2.12/version /dependency dependency groupIdjunit/groupId artifactIdjunit/artifactId version4.12/version scopetest/scope /dependency !--连接池-- dependency groupIdcom.alibaba/groupId artifactIddruid/artifactId version1.1.10/version /dependency !--mysql 驱动包-- dependency groupIdmysql/groupId artifactIdmysql-connector-java/artifactId version5.1.6/version /dependency dependency groupIdorg.springframework/groupId artifactIdspring-test/artifactId version5.0.2.RELEASE/version scopetest/scope /dependency /dependencies创建数据库创建表结构CREATE TABLE account ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL, money double DEFAULT NULL, PRIMARY KEY (id) USING BTREE ) ENGINE InnoDB AUTO_INCREMENT 9 CHARACTER SET utf8mb4 COLLATE utf8mb4_bin ROW_FORMAT Compact; INSERT INTO account VALUES (1, 小明, 100); INSERT INTO account VALUES (2, 小红, 120); INSERT INTO account VALUES (3, 小丽, 135); INSERT INTO account VALUES (4, 李华, 85); INSERT INTO account VALUES (5, 李莉, 110); INSERT INTO account VALUES (6, 熊大 , 500); INSERT INTO account VALUES (7, 熊二, 900); INSERT INTO account VALUES (8, 小丽, 500);编写 JavaBean 的类 Accountpublic class Account implements Serializable { private Integer id; private String name; private Double money; public Integer getId() { return id; } public void setId(Integer 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 }; } }Serializable 是 Java 中的一个标记给类打上标记接口其核心功能是支持对象的序列化与反序列化操作从而突破对象在内存中的存储限制补充对象序列化是指将内存中的 Java 对象其状态包括成员变量的值、类信息等转换为字节流的过程序列化流是 Java IO 体系中专门用于实现对象转换成字节流和字节流转换成对象的工具类由于内存中的对象是临时的JVM 退出后就会消失且无法直接跨进程跨网络传递序列化的核心价值就是打破对象的内存束缚。编写 AccountDao 的接口和实现类public interface AccountDao { public ListAccount findAll(); }public class AccountDaoImpl implements AccountDao{ // 注入连接池对象 private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource dataSource; } /** * 使用原始的JDBC程序查询所有数据 */ public ListAccount findAll() { ListAccount list new ArrayListAccount(); Connection connection null; PreparedStatement stmt null; ResultSet rs null; try { // 获取连接 connection dataSource.getConnection(); // 编写 sql 语句 String sql select * from account; // 预编译 stmt connection.prepareStatement(sql); // 查询 rs stmt.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 (SQLException e) { e.printStackTrace(); }finally { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; } }编写 AccountService 的接口和实现类并实现依赖注入public interface AccountService { public ListAccount findAll(); }public class AccountServiceImpl implements AccountService { // 依赖注入 private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao accountDao; } /** * 查询所有的数据 */ public ListAccount findAll() { return accountDao.findAll(); } }在资源文件夹下编写配置文件 applicationContext1.xml?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd !--配置连接池-- bean iddataSource classcom.alibaba.druid.pool.DruidDataSource property namedriverClassName valuecom.mysql.jdbc.Driver/ property nameurl valuejdbc:mysql:///ssm / property nameusername valueroot / property namepassword valueroot / /bean !--管理 bean-- bean idaccountService classcom.qcby.service.impl.AccountServiceImpl property nameaccountDao refaccountDao / /bean bean idaccountDao classcom.qcby.dao.impl.AccountDaoImpl property namedataSource refdataSource / /bean /beans编程测试程序public class Demo2 { Test public void run1(){ ApplicationContext ac new ClassPathXmlApplicationContext(applicationContext1.xml); AccountService accountService (AccountService) ac.getBean(accountService); // 调用方法 ListAccount list accountService.findAll(); for (Account account : list) { System.out.println(account); } } }实现效果如下IOC的注解开发方式半注解开发方式依赖依赖没有变化编写接口和实现类public interface AdminService { public void hello(); }Component(value as) public class AdminServiceImpl implements AdminService { public void hello() { System.out.println(Hello IOC 注解...); } }在需要管理的类上添加Component 注解作用与bean idus classcom.qcby.service.impl.UserServiceImpl/ 相同编写配置文件 applicationContext_anno.xml重点是开启注解扫描?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xmlns:contexthttp://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 !--开启注解扫描 com.qcby所有的包中的所有的类 -- context:component-scan base-packagecom.qcby / /beans编写测试方法public class Demo3 { Test public void run1(){ // 工厂 ApplicationContext ac new ClassPathXmlApplicationContext(applicationContext_anno.xml); // 获取对象 AdminService adminService (AdminService) ac.getBean(as); adminService.hello(); } }实现效果总结常用的注解Bean管理类常用的注解Component 通用的组件标识可将任意类标识为 Spring 容器管理的 BeanController 用于标识表现层的类负责接收用户请求并处理响应Service 用于标识业务逻辑层的类封装核心业务处理逻辑Repository 用于标识数据持久层的类负责数据的查询与存储除标识 Bean 外还能自动转换数据访问层的异常这些注解均用于类级别使用位置与对应层级匹配核心功能与 Component 一致注解在不指定 value 属性时默认会将当前类名的首字母小写作为该 Bean 在 Spring 容器中的 ID若需要自定义 Bean 名称可通过 value 属性指定如Service(value userManager)或简写为Service(userManager)。依赖注入常用的注解注入普通类型Value 注入基本类型、字符串或配置文件中的属性值注入引用数据类型Autowired 默认按类型进行自动装配当容器中存在唯一匹配类型的 Bean 时直接注入可用于构造方法、成员变量、setter方法上Qualifier 配合 Autowired 一起使用按名称注入 Bean解决同类型多个 Bean 的冲突Resource Java提供的注解也被支持使用 name 属性按名称注入对象注入普通类型Value 用于注入基本类型、字符串类型注入引用数据类型Autowired 由 Spring 提供默认按类型自动装配。当容器中存在唯一匹配类型的 Bean 时直接注入可用于构造方法、成员变量、setter 方法上若存在多个同类型 Bean需配合 Qualifier 使用否则会报错默认要求注入对象必须存在可通过required false设置为非必须Qualifier 需与 Autowired 配合使用通过value属性指定 Bean 的名称ID实现按名称注入解决同类型多个 Bean 的装配冲突Resource 由 Java EE 规范提供Spring 也支持该注解。默认按名称注入通过name属性指定 Bean 名称若未指定name则默认取属性名匹配若按名称未找到会自动切换为按类型注入需注意与 Autowired 默认行为的区别。生命周期作用范围注解Scope 生命周期注解常用取值为 singleton默认值单实例和 prototype多例初始化方法和销毁方法注解PostConstruct 标记销毁方法相当于XML配置中bean标签的destroy-method属性PreDestroy 标记初始化方法相当于XML配置中bean标签的init-method属性用于标注Bean实例化并完成依赖注入后需要执行的初始化方法具体代码示例Component(value c) public class Mobile { Value(奥迪) private String cname; Value(value 400000) private Double money; Autowired private Person person; /** * Car 对象创建完成后调用 init 方法进行初始化操作 */ PostConstruct public void init(){ System.out.println(操作...); } Override public String toString() { return Car{ cname cname \ , money money , person person }; } }Component(value person) public class Person { Value(张三) private String pname; Override public String toString() { return Person{ pname pname \ }; } }applicationContext_anno.xml?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xmlns:contexthttp://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 !--开启注解扫描 com.qcby.所有的包中的所有的类 -- context:component-scan base-packagecom.qcby / /beanspublic class Demo4 { Test public void run1(){ // 工厂 ApplicationContext ac new ClassPathXmlApplicationContext(applicationContext_anno.xml); // 获取对象 Mobile mobile (Mobile) ac.getBean(c); System.out.println(mobile); } }对于Mobile类其在 Spring 容器中的生命周期流程如下① Spring 容器通过组件扫描发现Mobile类执行构造方法创建其实例② 容器为Mobile实例注入依赖通过Value注入cname和money通过Autowired注入person对象③ 当所有依赖注入完成后容器检测到init方法被PostConstruct标注立即调用init方法执行初始化操作④ 初始化完成后Mobile实例成为 “可用状态”存入 Spring 容器中⑤ 当测试代码 ac.getBean(c) 获取Mobile实例时容器直接返回已初始化完成的 Bean。测试代码的执行顺序当new ClassPathXmlApplicationContext(...)执行时Spring 容器启动并完成上述①-④的所有流程包括调用init方法之后ac.getBean(c)获取到的是已经初始化完成的Mobile实例调用System.out.println(mobile)时才打印其属性信息。实现效果纯注解开发方式纯注解方式是当前微服务架构开发的主流模式其核心目标就是通过注解和配置类替代传统的 XML 配置文件让配置更简洁、更贴近代码逻辑同时更适合微服务架构的灵活性和可扩展性需求。编写实体类Component public class Order { Value(北京) private String address; Override public String toString() { return Order{ address address \ }; } }编写配置类 SpringConfig用于替换掉 applicationContext_anno.xml 配置文件Configuration ComponentScan(value com.qcby) public class SpringConfig { }Configuration 标识当前类是Spring 配置类相当于 XML 配置文件的根节点Spring 会将该类视为配置信息的载体类中被Bean标注的方法会被解析其返回值将作为 Bean 注册到 Spring 容器中。ComponentScan(value com.qcby) 指定 Spring 自动扫描组件的包路径相当于 XML 中的Spring 会扫描指定包及其子包下所有被Component 等标注的类自动将它们注册为容器中的 Bean如果不指定value默认扫描当前配置类所在的包及其子包。测试方法的编写public class Demo5 { Test public void run1(){ // 创建工厂加载配置类 ApplicationContext ac new AnnotationConfigApplicationContext(SpringConfig.class); // 获取到对象 Order order (Order) ac.getBean(order); System.out.println(order); } }ApplicationContext 是 Spring 的核心容器接口负责管理 Bean 的创建、依赖注入、生命周期等核心功能AnnotationConfigApplicationContext 是 ApplicationContext 的实现类专门用于加载基于注解的配置类参数 SpringConfig.class 指定要加载的配置类容器会根据该类中的Configuration、ComponentScan、Bean等注解初始化 Bean。实现效果我们看如下代码Configuration ComponentScan(value com.qcby) Import(value {SpringConfig2.class}) public class SpringConfig { //将第三方的类交给Spring框架管理 Bean(namedataSource) public DataSource createDataSource(){ DruidDataSource dataSource new DruidDataSource(); dataSource.setDriverClassName(com.mysql.jdbc.Driver); dataSource.setUrl(jdbc:mysql:///ssm); dataSource.setUsername(root); dataSource.setPassword(root); return dataSource; } }Import 用于导入其他配置类相当于XML中的可以导入多个配置类value 属性接收的是一个 Class 数组用逗号隔开。除了使用Import注解导入多个配置类也可在创建工厂时直接加载多个配置文件ApplicationContext ac new AnnotationConfigApplicationContext(SpringConfig.class,SpringConfig2.class);Bean 注解用于将第三方的类交给 Spring 框架管理指定 Bean 的 name 属性为 dataSource若不指定 name默认名称为方法名即 createDataSource为什么需要这样做DruidDataSource是第三方类我们无法修改其源码添加Component等注解因此必须通过Bean方法手动创建对象并注册到 Spring 容器中使其能被其他 Bean 依赖注入。Spring框架整合JUnit单元测试当需要测试 Spring 管理的 Bean 时若不借助框架整合每次都需要手动编写创建 Spring 上下文如ApplicationContext、加载配置文件等重复代码操作比较繁琐。Spring 通过 spring-test 模块提供了整合 JUnit 单元测试的技术能自动加载 Spring 上下文无需手动创建和配置可直接注入待测试的 Bean 进行测试从而显著简化测试开发流程。需要先有 Junit 单元测试环境再导入 spring-test 的坐标依赖dependency groupIdjunit/groupId artifactIdjunit/artifactId version4.12/version scopetest/scope dependency dependency groupIdorg.springframework/groupId artifactIdspring-test/artifactId version5.0.2.RELEASE/version scopetest/scope /dependency编写类和方法把该类交给 IOC 容器进行管理public class User { public void sayHello(){ System.out.println(Hello....); } }编写配置文件 applicationContext_test.xml?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd !--整合单元测试-- bean iduser classcom.qcby.model.User/ /beans编写测试代码RunWith(value SpringJUnit4ClassRunner.class) // 测试单元 ContextConfiguration(value classpath:applicationContext_test.xml) // 加载类路径下的配置文件 public class Demo6 { Autowired private User user; Test public void run1(){ user.sayHello(); } }RunWith(SpringJUnit4ClassRunner.class) 指定 JUnit 4 的测试运行器为 Spring 提供的SpringJUnit4ClassRunner使其能在测试前自动初始化 Spring 上下文ContextConfiguration 指定 Spring 配置文件或配置类的位置告诉 Spring 从哪里加载上下文常用属性locations指定 XML 配置文件路径如classpath:applicationContext.xmlclasses指定 Java 配置类如Configuration标注的类下面的纯注解方式用的是该属性实现效果如下Spring整合单元测试的纯注解方式编写类和方法Component public class Customer { public void save(){ System.out.println(保存客户...); } }编写配置类Configuration ComponentScan(value com.qcby) public class SpringConfig3 { }编写测试方法RunWith(SpringJUnit4ClassRunner.class) ContextConfiguration(classes SpringConfig3.class) public class Demo7 { Autowired private Customer customer; Test public void run1(){ customer.save(); } }注意点在 Spring 框架整合 JUnit 单元测试时无需手动编写创建工厂、加载配置文件以及调用getBean()获取对象的代码。这些操作实际上仍然存在只是由 Spring Test 框架自动完成了spring-test 模块通过注解和专用测试运行器将这些重复性工作封装到框架内部实现了自动化执行。没有整合 JUnit 时测试 Spring 管理的 Bean 需要手动创建Spring 的核心工厂 ApplicationContext代码如下public class UserServiceTest { public static void main(String[] args) { // 手动创建工厂 ApplicationContext context new ClassPathXmlApplicationContext(applicationContext.xml); // 手动获取Bean UserService userService context.getBean(UserService.class); // 测试逻辑 userService.test(); } }整合 JUnit 后通过RunWith(SpringJUnit4ClassRunner.class)注解测试运行器会在测试方法执行前自动创建ApplicationContext无需手动编写创建代码。手动测试时需要显式指定配置文件路径如ClassPathXmlApplicationContext(applicationContext.xml)整合后通过ContextConfiguration 指定配置文件 / 配置类位置框架会自动根据配置加载 Bean 定义无需手动调用加载方法。手动测试时需要通过context.getBean()获取目标对象整合后直接使用Autowired注解在测试类中声明需要的 BeanSpring 会自动从上下文已创建的工厂中找到对应的对象并注入替代了手动调用getBean()。