Spring-IoC-DI-基于注解方式的依赖注入-(案例二:基于注解方式实现属性注入)@Value普通类型属性

(1)

package com.orzjiangxiaoyu.spring.test1;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author orz
 * @create 2020-08-16 22:44
 */
@Component(value = "book")
public class Book {
    @Value(value = "金庸")
    private String name;
    @Value(value = "射雕英雄传")
    private String author;

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}

(2)



       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

    
    
    package="com.orzjiangxiaoyu.spring">

(3)

package com.orzjiangxiaoyu.spring.test1;

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


/**
 * @author orz
 * @create 2020-08-16 17:06
 */
public class Test1 {
  
    @Test
    public void test2()
    {
        //1.加载spring配置文件
        ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
        //2.获取配置文件的创建对象
        Book book = context.getBean("book", Book.class);

        System.out.println(book);

    }
}

(4)

Book{name='金庸', author='射雕英雄传'}

 

你可能感兴趣的:(Spring-IoC-DI-基于注解方式的依赖注入-(案例二:基于注解方式实现属性注入)@Value普通类型属性)