《Pro Spring》学习笔记之使用properties文件进行依赖注入

前端之家收集整理的这篇文章主要介绍了《Pro Spring》学习笔记之使用properties文件进行依赖注入前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

JavaBean:

package ch2;

public class Student {
privateStringstuName;
privateCoursestuCourse;
publicCoursegetStuCourse()@H_301_38@...
{
returnstuCourse;
}

publicvoidsetStuCourse(CoursestuCourse){
this.stuCourse=stuCourse;
}

publicStringgetStuName(){
returnstuName;
}

publicvoidsetStuName(StringstuName){
this.stuName=stuName;
}

}



package ch2;

public class Course {
privateStringcourseName;

publicStringgetCourseName(){
returncourseName;
}


publicvoidsetCourseName(StringcourseName){
this.courseName=courseName;
}

}

beans.properties


#配置Course
course.class=ch2.Course
#配置Course.courseName
course.courseName = shuxue
#配置Student
student.class=ch2.Student
#配置Student引用属性stuCourse
student.stuCourse(ref)=course
#配置Student.stuName
student.stuName=gaoxiang

测试代码

主要使用DefaultListablebeanfactory和PropertiesBeanDefinitionReader这两个核心类

package ch2;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.springframework.beans.factory.beanfactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListablebeanfactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;



public class TestSpring {
publicstaticvoidmain(Stringargs[])throwsException{
//获取beanfactory
beanfactoryfactory=(beanfactory)getbeanfactory();
Studentstu
=(Student)factory.getBean("student");//这里只获取student对象,student对象中的course对象在properties文件中进行注入
System.out.println(stu.getStuName()+"'scourseis"+stu.getStuCourse().getCourseName());

}

publicstaticBeanDefinitionRegistrygetbeanfactory(){
//获取beanfactory
DefaultListablebeanfactoryfactory=newDefaultListablebeanfactory();
//创建一个definitionreader
PropertiesBeanDefinitionReaderrd=newPropertiesBeanDefinitionReader(factory);

Propertiesprops
=newProperties();
try{
Stringrealpath
="";
//加载配置项
realpath=System.getProperty("user.dir")+File.separator+"src"+File.separator+"ch2"+File.separator+"bean_zh_CN.properties";
props.load(
newFileInputStream(realpath));
}
catch(Exceptione){
e.printStackTrace();
returnnull;
}



rd.registerBeanDefinitions(props);
returnfactory;
}

}

运行结果:

gaoxiang 's course is shuxue 正如我们锁期望的那样

猜你在找的设计模式相关文章