Spring 框架:上手配置一个Bean

目录

1. 准备一个纯净的POJO

2. 通过xml配置一个bean

3. 通过Spring上下文获取Bean


 

1. 准备一个纯净的POJO

这里的Employee类没有什么特殊的地方,我们只定义了一个字段,name

package com.test; 

public class Employee {
    
    private String name;

    public String getName() { 
        return name;
    }

    public void setName(String name) { 
        this.name = name;
    }

    public void displayName() { 
        System.out.println(name);
    } 

}

 

2. 通过xml配置一个bean

我们通过xml文件将employee配置成了一个Bean。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

    <bean id="employee" class="com.test.Employee">
        <property name="name" value="test spring"></property>
    </bean>

</beans>

 

3. 通过Spring上下文获取Bean

ApplicationContext是获取Bean的一个途径,通过ClassPathXMLApplicationContext读取xml配置文件构建。

ApplicationContext的getBean的方法可以获取Bean。

package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Customer {
    
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Employee obj = (Employee) context.getBean("employee");
        obj.displayName(); 
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值