Java Spring数据单元 Java Spring数据单元配置过程解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java Spring数据单元 Java Spring数据单元配置过程解析

手撕高达的村长   2021-01-28 我要评论

基本原理 - 容器和bean

在Spring中,那些组成你应用程序的主体(backbone)及由Spring IoC容器所管理的对象,被称之为bean。 简单地讲,bean就是由Spring容器初始化、装配及管理的对象,除此之外,bean就与应用程序中的其他对象没有什么区别了。

也就是说,其实spring 就是在加载配置文件beans.xml的时候,通过反射机制,去实例化<bean>标签里面的类的过程。这里可以通过在类的默认无参构造方法中写点东西判断出来。

1. 配置元数据

基于XML的配置元数据的基本结构:beans.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
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="..." class="...">
  <!-- collaborators and configuration for this bean go here -->
 </bean>

 <bean id="..." class="...">
  <!-- collaborators and configuration for this bean go here -->
 </bean>

 <!-- 更多的bean的时候 在引用的xml文件一定是要带spring dtd头的文件-->
  <import resource="services.xml"/>
</beans>

services.xml

在配置文件里面命名其实id 和name都是一样的

<?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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
 <bean id="userService" name="userService" class="com.sun.service.UserService">
<property name="name">
 <value>sunxin</value>
</property>
</bean>
</beans>

2. 实例化容器

ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"beans.xml"});

3. bean的别名

<!--name指向的是已经存在该id的bean,alias是给给该bean命的别名-->
<alias name="userService" alias="user"/>

调用可以通过:

UserService us = (UserService) app.getBean("user");

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们