济宁网站建设,个人网站建立教程,wordpress手机登录插件,网站设置为应用程序原文网址#xff1a;Spring注册Bean系列--方法1#xff1a;Component_IT利刃出鞘的博客-CSDN博客
简介
本文介绍Spring注册Bean的方法#xff1a;Component。
注册Bean的方法我写了一个系列#xff0c;见#xff1a;Spring注册Bean(提供Bean)系列--方法大全_IT利刃出鞘…原文网址Spring注册Bean系列--方法1Component_IT利刃出鞘的博客-CSDN博客
简介
本文介绍Spring注册Bean的方法Component。
注册Bean的方法我写了一个系列见Spring注册Bean(提供Bean)系列--方法大全_IT利刃出鞘的博客-CSDN博客
方法概述
在bean类上加Component即可。 (Controller/Service/Repository也可以因为它里边包含Component)
Spring默认会扫描SpringBootApplication注解所在包及其子包的类将这些类纳入到spring容器只要类有Component注解即可。
这个扫描的位置是可以指定的例如
SpringBootApplication(scanBasePackagescom.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 {Autowiredprivate MyBean myBean;GetMapping(/test)public String test() {return myBean.sayHello();}
}结果