首页 > 代码库 > Spring依赖注入的Setter注入(通过get和set方法注入)

Spring依赖注入的Setter注入(通过get和set方法注入)

Spring依赖注入的Setter注入(通过get和set方法注入)

导入必要的jar包(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.entity.User">
        <property name="names">
            <value>1111</value>
        </property>
        <property name="ages">
            <value>30</value>
        </property>
    </bean>
</beans>

2.Setter注入

package com.cc8w;

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

import com.cc8w.entity.User;

public class Test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User)context.getBean("user");
        System.out.println(user);
    }

}

java的数据类型

package com.cc8w.entity;

public class User {
    private String names;
    private int ages;
    public String getNames() {
        return names;
    }
    public void setNames(String names) {
        this.names = names;
    }
    public int getAges() {
        return ages;
    }
    public void setAges(int ages) {
        this.ages = ages;
    }    
    
}  

结果:

技术分享

Spring依赖注入的Setter注入(通过get和set方法注入)