Spring-IoC-DI-基于注解方式的依赖注入-(案例六:使用@Value注解实现普通类型自动装配)
案例六:使用@Value注解实现普通类型自动装配
(1)创建一个简单类
@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)配置文件,开启组件扫描
<context:component-scan base-package="com.orzjiangxiaoyu.spring"></context:component-scan>
(3)测试
@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='射雕英雄传'}