Spring学习笔记--基于XML配置bean的基本方式

基于XML配置bean的基本方式

 

代码如下:

<?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.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>
      <!-- more bean definitions go here -->
</beans>

 


其中

id=””表示你对bean的命名;

class=””表示的是bean类的路径;

配置中是可以配置多个bean的

 

示例:

Bean

//Hello.java
package com.wenj.services;

public interface Hello {
public void sayHello();
}

//HelloImpl.java

package com.wenj.servicesimpl;

import com.wenj.services.Hello;
public class HelloImpl implements Hello {
@Override
public void sayHello() {
System.out.println("Hello World");
}
}


 

配置bean

代码如下:

<?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.xsd">        
<bean id="hello" class="com.wenj.servicesimpl.HelloImpl"></bean>  
</beans>


 

Test

新建一个jUnit test case

 

在里面添加如下代码

@Test
public void test(){
ApplicationContext cxt = new ClassPathXmlApplicationContext("com/wenj/resources/beans.xml");
Hello h = (Hello) cxt.getBean("helloImpl");
h.sayHello();
}


 

实例化一个Spring Ioc容器

 

注意到以上的测试代码

ApplicationContext cxt = new ClassPathXmlApplicationContext("com/wenj/resources/beans.xml");

此代码片段式就是用于实例化Spring IoC容器的同时容器是可以加载多个xml文件的,:

ApplicationContext context =

    new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

其中就可以加载services.xml和daos.xml

使用容器获取bean对象

Hello h = (Hello) cxt.getBean("helloImpl");

这里通过id来获取容器中的bean对象

 

至此运行,可以在控制台输出

Hello World!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值