首页 > 编程语言 > 详细

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

时间:2020-08-16 23:08:30      阅读:150      评论:0      收藏:0      [点我收藏+]

(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)

<?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: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">

    <!-- 开始组件扫面   -->
    <!-- 1.如果扫描多个包,多个包使用逗号隔开
         2.扫描包上层目录
     -->
    <context:component-scan base-package="com.orzjiangxiaoyu.spring"></context:component-scan>

</beans>

(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普通类型属性

原文:https://www.cnblogs.com/orzjiangxiaoyu/p/13514914.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!