Spring-01-helloSpring

82 阅读1分钟

基础配置

编写spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
       <!--注册实体类-->
    <bean id="testHello" class="pojo.Test">
        <property name="str" value="hello"/>
    </bean>
</beans>

编写对应的实体类

package pojo;

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

public class Test {
    private String str;

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Test{" +
                "str='" + str + '\'' +
                '}';
    }

调用

    public static void main(String[] args) {
        ApplicationContext Context = new ClassPathXmlApplicationContext("Beans.xml");
        Test testHello = (Test) Context.getBean("testHello");
        System.out.println(testHello);
    }
}

流程

bean 标签代表着类对象,通过无参构造创建对象,通过setter方法按配置文件给属性赋值

属性是对象时,可以通过ref来动态引用