Spring注册Bean系列--方法1:@Component
作者:小教学发布时间:2023-10-02分类:程序开发学习浏览:469
导读:原文网址:Spring注册Bean系列--方法1:@Component_IT利刃出鞘的博客-CSDN博客简介本文介绍Spring注册Bean的方法:@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();
}
}
结果

- 程序开发学习排行
- 最近发表
-
- WordPress 应用:如何修改模版头部文件中的 wp_head() - Web前端
- SEO 优化:YouTube SEO Plugin 提升影片流量 - Web前端
- 使用 React 服务器组件在 Next.js 13 中进行国际化 - Web前端
- 3 个意想不到的技术 SEO 问题示例(以及如何解决它们) - Web前端
- Vue 技术专题:Suspense、路由模式与单元测试实践 - Web前端
- 如何防止 WordPress SQL 注入攻击? - Web前端
- SEO 优化:如何围绕技术SEO框架以构建和制定策略? - Web前端
- SEO优化:YouTube SEO 关键词研究工具 - Web前端
- 2025 年帮助代理机构提升客户业绩的 14 款最佳 SEO 工具 - Web前端
- 客户端:服务器之间设置本地 DNS 服务器 - Web前端


