Spring入门&控制反转(或依赖注入)&AOP的关键概念& 多配置文件&与web集成(二)

简介: Spring入门&控制反转(或依赖注入)&AOP的关键概念& 多配置文件&与web集成

2) Student

public class Student extends Person {
  private String name;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  @Override
  public String toString() {
    return "Demo [name=" + name + "]";
  }
}

3) 配置文件

<bean id="student" class="org.lisen.springdemo.model.Student" parent="person">
    <property name="name">
      <value>张三</value>
    </property>
  </bean>
  <bean id="person" class="org.lisen.springdemo.model.Person" abstract="true">
    <property name="phone">
      <value>139751878778</value>
    </property>
  </bean>

4) 通过Spring的ApplicationContext获取Bean

public class SpringDemo {
  public static void main(String[] args) {
    ApplicationContext cxt = new ClassPathXmlApplicationContext("spring.xml");
    Student student = (Student)cxt.getBean("student");
    System.out.println(student.getName());
    System.out.println(student.getPhone());
  }
}

4.4.3 使用有参数构造方法创建javaBean

constructor-arg

1) Worker

public class Worker extends Person {
  private String workName;
  public Worker(String workName) {
    this.workName = workName;
  }
  public String getWorkName() {
    return workName;
  }
  public void setWorkName(String workName) {
    this.workName = workName;
  }
}

2)配置文件

<bean id="worker" class="org.lisen.springdemo.model.Worker" parent="person">
    <constructor-arg name="workName">
      <value>王小</value>
    </constructor-arg>
    <!-- 第二种方式
    <constructor-arg index="0">
      <value>王小</value>
    </constructor-arg>
     -->
  </bean>

3) 通过Spring的ApplicationContext获取Bean

public class SpringDemo {
  public static void main(String[] args) {
    ApplicationContext cxt = new ClassPathXmlApplicationContext("spring.xml");
    Student student = (Student)cxt.getBean("student");
    System.out.println(student.getName());
    System.out.println(student.getPhone());
    //构造函数注入
    Worker worker = (Worker)cxt.getBean("worker");
    System.out.println(worker.getWorkName());
  }
}

4.4.4 init-method:指定bean的初始化方法

  1. 修改上面的Student类,加入一个init方法,注意该方法不能有参数
public class Student extends Person {
  private String name;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  @Override
  public String toString() {
    return "Demo [name=" + name + "]";
  }
  //init方法,不能有参数
  public void init() {
    System.out.println("Student init ....");
  }
}

2) 修改Student类对应的配置文件

<bean id="student" class="org.lisen.springdemo.model.Student" parent="person" init-method="init">
    <property name="name">
      <value>张三</value>
    </property>
  </bean>

3) 运行原来的测试用例,会发生后台打印“Student init ....“,表示init-method正常调用。

4.4.5 复杂属性的配置

1) JavaBean属性注入

<bean id="student" class="org.lisen.springdemo.model.Student" parent="person" init-method="init">
    <property name="name">
      <value>张三</value>
    </property>
    <property name="addr" ref="addr"/>
  </bean>
  <bean id="addr" class="org.lisen.springdemo.model.Addr">
    <property name="city">
      <value>长沙</value>
    </property>
  </bean>

java部分代码比较简单,请根据配置文件自行完成。

2)List或数组

声明属性

private int[] arr;
 private List list;

配置文件

  <property name="list">
      <list>
        <value>123</value>
        <value>456</value>
        <value>789</value>
        <value>asd</value>
      </list>
    </property>

3)Map

private Map map;

配置文件

 <property name="map">
      <map>
        <entry key="aa" value="123"/>
        <entry key="bb" value="456"/>
        <entry key="cc" value="789"/>
      </map>
    </property>

4.Properties

private Properties prop;

配置文件

  <property name="prop">
      <props>
        <prop key="dd">qwer</prop>
        <prop key="ee">tyu</prop>
        <prop key="ff">iop</prop>
      </props>
    </property>

5. 多配置文件

系统一般会被分成多个模块,可以为每个模块配置一个配置文件,便于管理,在版本控制软件中也可以减少冲突

spring-a.xml 假设为a模块的配置文件

<?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:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
  <bean id="student" class="org.lisen.springdemo.model.Student" parent="person" init-method="init">
    <property name="name">
      <value>张三</value>
    </property>
    <property name="addr" ref="addr"/>
  </bean>
  <bean id="addr" class="org.lisen.springdemo.model.Addr">
    <property name="city">
      <value>长沙</value>
    </property>
  </bean>
  <bean id="person" class="org.lisen.springdemo.model.Person" abstract="true">
    <property name="phone">
      <value>139751878778</value>
    </property>
  </bean>
  <bean id="worker" class="org.lisen.springdemo.model.Worker" parent="person">
    <constructor-arg name="workName">
      <value>王小</value>
    </constructor-arg>
    <!-- 第二种方式
    <constructor-arg index="0">
      <value>王小</value>
    </constructor-arg>
     -->
  </bean>
</beans>

spring.xml 为总的spring配置文件, 在总配置文件中导入其他模块即可。

<?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:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
  <import resource="spring-a.xml"/>
</beans>

6. 与web集成

6.1 集成配置

在web.xml中加入如下配置:

 <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
     <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

6.2 获取配置的Bean

/**
 * 用于简化Bean的获取.
 * 
 * ApplicationContextAware接口:
 * 实现了这个接口的bean,当spring容器初始化的时候,会自动的将ApplicationContext注入进来
 * 
 * @author Administrator
 */
public final class SpringBeanUtil implements ApplicationContextAware {
  private SpringBeanUtil() {
  }
  private static ApplicationContext cxt;
  @Override
  public void setApplicationContext(ApplicationContext appContext) throws BeansException {
    cxt = appContext;
  }
  /**
   * 根据Bean的id来获取Bean对象
   * @param id 配置文件中的bean的id属性
   * @return Object
   */
  @SuppressWarnings("unchecked")
  public static <T> T getBean(String id) {
    return (T)cxt.getBean(id);
  }
} 

配置文件

     <bean 
class="org.lisen.springdemo.util.SpringBeanUtil"/>
相关文章
|
人工智能 Java API
Spring AI 实战|Spring AI入门之DeepSeek调用
本文介绍了Spring AI框架如何帮助Java开发者轻松集成和使用大模型API。文章从Spring AI的初探开始,探讨了其核心能力及应用场景,包括手动与自动发起请求、流式响应实现打字机效果,以及兼容不同AI服务(如DeepSeek、通义千问)的方法。同时,还详细讲解了如何在生产环境中添加监控以优化性能和成本管理。通过Spring AI,开发者可以简化大模型调用流程,降低复杂度,为企业智能应用开发提供强大支持。最后,文章展望了Spring AI在未来AI时代的重要作用,鼓励开发者积极拥抱这一技术变革。
4764 71
Spring AI 实战|Spring AI入门之DeepSeek调用
|
缓存 安全 Java
《深入理解Spring》过滤器(Filter)——Web请求的第一道防线
Servlet过滤器是Java Web核心组件,可在请求进入容器时进行预处理与响应后处理,适用于日志、认证、安全、跨域等全局性功能,具有比Spring拦截器更早的执行时机和更广的覆盖范围。
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
1001 2
|
存储 安全 Java
如何在 Spring Web 应用程序中使用 @SessionScope 和 @RequestScope
Spring框架中的`@SessionScope`和`@RequestScope`注解用于管理Web应用中的状态。`@SessionScope`绑定HTTP会话生命周期,适用于用户特定数据,如购物车;`@RequestScope`限定于单个请求,适合无状态、线程安全的操作,如日志记录。合理选择作用域能提升应用性能与可维护性。
532 1
|
存储 NoSQL Java
探索Spring Boot的函数式Web应用开发
通过这种方式,开发者能以声明式和函数式的编程习惯,构建高效、易测试、并发友好的Web应用,同时也能以较小的学习曲线迅速上手,因为这些概念与Spring Framework其他部分保持一致性。在设计和编码过程中,保持代码的简洁性和高内聚性,有助于维持项目的可管理性,也便于其他开发者阅读和理解。
347 0
|
Java 关系型数据库 MySQL
【Spring】【事务】初学者直呼学会了的Spring事务入门
本文深入解析了Spring事务的核心概念与使用方法。Spring事务是一种数据库事务管理机制,通过确保操作的原子性、一致性、隔离性和持久性(ACID),维护数据完整性。文章详细讲解了声明式事务(@Transactional注解)和编程式事务(TransactionTemplate、PlatformTransactionManager)的区别与用法,并探讨了事务传播行为(如REQUIRED、REQUIRES_NEW等)及隔离级别(如READ_COMMITTED、REPEATABLE_READ)。
1054 1
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
1029 0
|
前端开发 Java API
基于 Spring Boot 3 与 React 的 Java 学生信息管理系统从入门到精通实操指南
本项目基于Spring Boot 3与React 18构建学生信息管理系统,涵盖前后端开发、容器化部署及测试监控,提供完整实操指南与源码,助你掌握Java全栈开发技能。
758 0
|
Java API 微服务
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
1415 0

热门文章

最新文章