spring person

2021-04-14 15:27

阅读:698

标签:配置文件   set   tom   frame   core   col   类别   ons   tostring   

IOC: 由spring 进行创建、管理、配置

官网:https://docs.spring.io/spring/docs/5.2.7.RELEASE/spring-framework-reference/core.html#beans-child-bean-definitions

一个简单的例子

准配工作:导包

1、pojo实体类

package com.wt.pojo;

public class Person {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Person{" +
                "name=‘" + name + ‘\‘‘ +
                ‘}‘;
    }
}

2、配置元数据

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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    bean id="person" class="com.wt.pojo.Person">
        property name="name" value="tom"/>
     bean>

beans>

3、实例化容器

import com.wt.pojo.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void showResult(){
        ApplicationContext context = new ClassPathXmlApplicationContext( "beans.xml");
        // person 对应配置文件的 id
        Person person = (Person) context.getBean("person");
        String personString = person.toString();
        System.out.println(personString);
    }
}

 注意:name="name" value="tom"/>

value 是普通变量

ref 指向自定义的类别名

例子

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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

        bean id="daoHello" class="com.wt.dao.UserDaoHello" />
        bean id="daoImp" class="com.wt.dao.UserDaoImp" />
        bean id="serviceImp" class="com.wt.service.UserServiceImp">
            property name="userDao" ref="daoHello" />
        bean>

beans>

 

spring person

标签:配置文件   set   tom   frame   core   col   类别   ons   tostring   

原文地址:https://www.cnblogs.com/wt7018/p/13336683.html


评论


亲,登录后才可以留言!