使用bean注解装配javabean,只需要在已经被装配的类中定义一个装配指定bean的函数,然后在这个函数上方声明bean的名称,这样spring扫描到这个被装配的bean之后,会自动执行其中被@bean声明的函数,完成返回类型对象的装配,对象名就是bean中声明的名称
实现步骤
- 定义一个简单java对象book--->id name
- 定义一个执行装配函数的类bookController
- 将其使用注解装配
- 定义装配函数
- 测试
代码
- 定义一个简单java对象book--->id name
-
package com.spring.test.bean; public class Book { private int id; private String name; public Book(int id, String name) { super(); this.id = id; this.name = name; } public Book() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + "]"; } }
-
- 定义一个执行装配函数的类bookController
- 将其使用注解装配
- 定义装配函数
-
package com.spring.test.controller; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import com.spring.test.bean.Book; @Component(value="bookController") public class BookController { @Bean(name = "book2") public Book fillBook() { Book book = new Book(1002, "《明哲言行录》"); return book; } }
- 定义组件扫描器
-
package com.spring.test.config; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = {"com.spring.test.bean", "com.spring.test.controller"}) public class BeanConfig { }
-
- 测试
-
package com.spring.test.ioc; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.test.bean.Book; import com.spring.test.bean.User; import com.spring.test.config.BeanConfig; public class Test { public static void main(String[] args) { /* * * * */ new Test().testIOC(); } @SuppressWarnings("resource") private void testIOC() { /* * * 如何使用IOC 定义普通java类,两个,且存在依赖关系 创建配置文件,定义依赖信息 使用IOC容器创建对象 根据配置信息创建容器 * 通过容器,根据类型ID创建对应的对象 通过得到的对象调用它自己的函数 关闭容器 */ ApplicationContext context = null; // context = new ClassPathXmlApplicationContext("spring-ioc.xml"); // Book book = (Book) context.getBean("book"); // System.out.println(book.toString()); context = new AnnotationConfigApplicationContext(BeanConfig.class); // User user = (User) context.getBean("user"); // System.out.println(user.toString()); Book book2 = (Book) context.getBean("book2"); System.out.println(book2.toString()); } }
-
来源:CSDN
作者:机器学习1.5
链接:https://blog.csdn.net/dyk2200364978dyk/article/details/104053905