Spring基础——使用XML配置一个Bean

这里解释一下为什么现在都流行注解开发了而依然还要来去了解xml配置文件,甚至很多博客都不愿意去写xml相关的配置。
官方文档里提出了注解开发的优势是在声明中已经提供了大量的上下文,从而让配置变短更简洁,而xml则可以在不需要动源代码的情况加队组件进行注入,更加符合POJO的思想理念,此外注解开发会让配置变得更加分散,难以控制。
注解注入是在XML注入之前进行的。
文章所用项目源码参考:java_spring_learn_repo

annotation_xml

  • 记得先导包,既然是IoC容器相关那就导入spring-context包
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.project.version>5.3.26</spring.project.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.project.version}</version>
    </dependency>
  </dependencies>

初始化XML文件

  • 这里手动创建一个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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="..." class="..."> 
        <!-- 这个bean的合作者和配置在这里 -->
    </bean>

    <!-- 更多bean 定义在这里 -->

</beans>
  • id: 属性是一个字符串,用于识别单个Bean定义。
  • class:属性定义了 Bean 的类型,并使用类的全路径名。、

当然,和bean关联的类也不能少
XMLBean

public interface XmlBean {
    public void pirintHello();
}

XMLBean的实现类

public class XmlBeanImpl implements XmlBean {
    @Override
    public void pirintHello() {
        System.out.println("bean hello world");
    }
}

bean.xml

<bean id="xmlBean" class="com.nobugnolife.bean.impl.XmlBeanImpl"/>

实例化Spring容器

  • 在Spring IoC容器中org.springframework.context.ApplicationContext接口负责管理配置组装bean,Spring提供了几个ApplicationContext 接口的实现,比如ClassPathXmlApplicationContext 或 FileSystemXmlApplicationContext。
  • 大多数应用场景不需要我们自己写代码实例化IoC容器的实例,有Spring Tools模板帮我们轻松实现,不过这里还是先了解一下。

实例化ApplicationContext

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
  • 如果是FileSystemXmlApplicationContext的话需要提供到当前项目的路径
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/main/resources/bean.xml");

获取指定Bean对象

  • ApplicationContext 提供了很多种获取Bean的模式,你可以通过bean的id或者name获取,也可以通过当前传入的class类型获取,也可以同时传入获取。
// XmlBean xmlBean = (XmlBean)applicationContext.getBean("xmlBean");
// XmlBean xmlBean = applicationContext.getBean("xmlBean",XmlBean.class);
XmlBean xmlBean = applicationContext.getBean(XmlBean.class);
  • 调用xmlBean方法
xmlBean.pirintHello();
  • 测试运行
    print_hello
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值