Spring利器之包掃描器


在學習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);
    }
}

這樣我們就不用再配置文件中寫很多配置的東西了直接用包掃描器為我們定義的屬性賦值了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM