zoukankan      html  css  js  c++  java
  • java Spring配置数据单元

    基本原理 - 容器和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"});

    2. bean的别名

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

    调用可以通过:

        UserService us  = (UserService) app.getBean("user");
  • 相关阅读:
    【Rust】文件操作
    【Rust】转义字符
    【Rust】原始标识符
    【Rust】字节数组
    【Rust】文档测试
    【Rust】外部函数接口
    【Rust】不安全操作
    【Rust】单元测试
    【Rust】集成测试
    WPF之ComboBox 安静点
  • 原文地址:https://www.cnblogs.com/sunxun/p/5407427.html
Copyright © 2011-2022 走看看