您的位置:首页技术文章
文章详情页

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

浏览:5日期:2022-08-19 15:08:26

基本原理 - 容器和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 class='...'> <!-- collaborators and configuration for this bean go here --> </bean> <bean 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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd'> <bean 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');

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。

标签: Java
相关文章: