spring利用扫描方式对bean的处理(对任何版本如何获取xml配置信息的处理)

利用扫描的方式将组件注入容器,就也可以不用操作bean来实例化对象了。

下面我做一个例子

我用的spring3.2.2版本的

首先写一个spring.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"

     xmlns:context="http://www.springframework.org/schema/context"

     xsi:schemaLocation="http://www.springframework.org/schema/beans

        http://www.springframework.org/schema/beans/spring-beans.xsd

         http://www.springframework.org/schema/context

         http://www.springframework.org/schema/context/spring-context.xsd">

 

<context:component-scan base-package="com.fish"/>//这里写包名。意思说只要在这个包里的bean都被我实例化了。

</beans>

 

其实这篇代码不难,但是对于新手学习还是有点难度的。因为spring的版本不一样。所以配置信息的内容会改变。如何获取自己版本对应的配置信息呢?首先明白所有框架你在从官网下载下来一般都有这3部分,第一lib文件存放所有jar包,第二个就是doc就是说明书,第三个就是例子。

你只要知道自己版本的说明书现在官网的都以网页形式给出。比如说我现在学习的是IOC

bean处理。那么我到找关于bean处理的网页,在浏览器里面查找,<xmlns:context一般就能找到了你要的模板例子了。这个复制粘贴到你的xml那绝对是100%正确的。什么版本都不用怕。

 

接着我写一个person.java

package com.fish;

 

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.stereotype.Service;

 

@Service   //类前面加个注解。而这文件本来就在com.fish包下,这样spring容器就知道你要实例化了

public class Person {

public String getName(){

       return name;

}

 

public voidsetName(String name) {

       this.name = name;

}

 

public void show(){

       System.out.println("aa");

}

}

下面我在写一个测试类吧

package com.fish;

 

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Test {

      

public static voidmain(String[] args) {

       ApplicationContext context =

                  newClassPathXmlApplicationContext("spring.xml");//spring激活,

                     Person person=(Person)context.getBean("person");//本来是靠bean来建立对象的,现在XML文件早就没有了。所以这个bean的名字。就是你要初始化的类名的小写开头。

                     person.show();//我们可以看到输出aa

}

}

原文地址:https://www.cnblogs.com/dyllove98/p/3199059.html