首页 > 技术文章 > Spring利器之包扫描器

System-out-println 2016-10-08 14:20 原文

在学习Spring这门技术中为了大大减少applicationContext.xml配置的代码量于是有了包扫描器。

闲话不多说我们马上来实现一下吧

 

示例架构如下:

第一步我们先来修改我们的配置applicationContext.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="cn.lxp.entity"></context:component-scan>
    </beans>

 

第二步我们先创建实体类StudentInfo

package cn.lxp.entity;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("info")
public class StudentInfo {
//赋值 @Value(
"Mr.DaPeng") private String Name;
//赋值 @Value(
"18") private String age; @Override public String toString() { return "StudentInfo [Name=" + Name + ", age=" + age + "]"; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }

 

 

第三步创建一个测试类SpringTest来测试我们的代码

package cn.lxp.test; 

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.lxp.entity.StudentInfo;



public class SpringTest {

    @Test
    public  void testOne(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
    
        StudentInfo stu=(StudentInfo)context.getBean("info");
    
        System.out.println(stu);
    }
}

这样我们就不用再配置文件中写很多配置的东西了直接用包扫描器为我们定义的属性赋值了

 

推荐阅读