首页 > 代码库 > java-Spring 管理bean例子

java-Spring 管理bean例子

Spring 通过2种方式管理bean

首先要导入Spring的包,(Spring.jar和commonslogging.jar) 或加载分开的...

在src目录下建立applicationContext.xml   (Spring 管理 bean的配置文件)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPEING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="user" class="com.cc8w.entiey.User"/>
</beans>

1.使用BeanFactory管理bean

2.使用ApplicationContext管理bean

package com.cc8w;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.cc8w.entiey.User;

public class TestBean {

    public static void main(String[] args) {
    
        //BeanFactory 管理bean
        Resource resource = new ClassPathResource("applicationContext.xml");
        BeanFactory factory =new XmlBeanFactory(resource);
        User user = (User) factory.getBean("user");
        System.out.println(user);
        
        //applicationContext 管理bean
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user1 = (User)context.getBean("user");
        System.out.println(user1);
        
    }

}

 

java的数据类型

package com.cc8w.entiey;

public class User {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
}

 

结果:

技术分享

呃.. 写错了,应该时entity.

Spring 控制反转 依赖注入 (配置初始化参数-实例化参数)

1.接口注入

2.Setter注入(推荐)

3.构造器注入

 

java-Spring 管理bean例子