- 用.properties文件配制
java Bean代码
- package org.beans;
- public class HelloBean {
- private String helloWorld;
- public String getHelloWorld() {
- return helloWorld;
- }
- public void setHelloWorld(String helloWorld) {
- this.helloWorld = helloWorld;
- }
- }
beans-config.properties文件
properties代码
- helloBean.class=org.beans.HelloBean
- helloBean.helloWorld=welcome
主程序代码
- package org.test;
- import org.beans.HelloBean;
- 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;
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.core.io.FileSystemResource;
- public class SpringTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- BeanDefinitionRegistry re=new DefaultListableBeanFactory();
- PropertiesBeanDefinitionReader reader=new PropertiesBeanDefinitionReader(re);
- //也可以用reader.loadBeanDefinitions(new ClassPathResource("beans-config.properties"));
- reader.loadBeanDefinitions(new FileSystemResource("org/properties/beans-config.properties"));
- BeanFactory factory=(BeanFactory)re;
- HelloBean hello=(HelloBean)factory.getBean("helloBean");
- System.out.println(hello.getHelloWorld());
- }
- }
2、在程序中直接编写程序
java 代码
- package org.test;
- import org.beans.HelloBean;
- import org.springframework.beans.MutablePropertyValues;
- 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.RootBeanDefinition;
- public class springMain {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //设置属性
- MutablePropertyValues properties=new MutablePropertyValues();
- properties.addPropertyValue("helloWorld","Hello,Weimin");
- //设置bean定义
- RootBeanDefinition definition=new RootBeanDefinition(HelloBean.class,properties);
- //注册bean定义与bean别名
- BeanDefinitionRegistry re=new DefaultListableBeanFactory();
- re.registerBeanDefinition("helloBean", definition);
- BeanFactory factory=(BeanFactory)re;
- HelloBean hello=(HelloBean)factory.getBean("helloBean");
- System.out.println(hello.getHelloWorld());
- }
- }