主页 > 软件开发  > 

Spring注册Bean系列--方法1:@Component

Spring注册Bean系列--方法1:@Component

原文网址:Spring注册Bean系列--方法1:@Component_IT利刃出鞘的博客-CSDN博客

简介

本文介绍Spring注册Bean的方法:@Component。

注册Bean的方法我写了一个系列,见:Spring注册Bean(提供Bean)系列--方法大全_IT利刃出鞘的博客-CSDN博客

方法概述

在bean类上加@Component即可。 (@Controller/@Service/@Repository也可以,因为它里边包含@Component)

Spring默认会扫描@SpringBootApplication注解所在包及其子包的类,将这些类纳入到spring容器,只要类有@Component注解即可。

这个扫描的位置是可以指定的,例如:

@SpringBootApplication(scanBasePackages="com.test.chapter4") 实例 要注册的类(Bean) package com.knife.entity; import org.springframework.stereotype.Component; @Component public class MyBean { public String sayHello() { return "Hello World"; } } 测试 package com.knife.controller; import com.knife.entity.MyBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @Autowired private MyBean myBean; @GetMapping("/test") public String test() { return myBean.sayHello(); } }

结果

标签:

Spring注册Bean系列--方法1:@Component由讯客互联软件开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Spring注册Bean系列--方法1:@Component