介绍
小编这次要给大家分享的是如何配置和使用Spring @ bean注解,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。
<强>使用说明强>
这个注解主要用在方法上,声明当前方法体中包含了最终产生豆实例的逻辑,方法的返回值是一个bean。这个bean会被弹簧加入到容器中进行管理,默认情况下豆的命名就是使用了bean注解的方法名.@Bean一般和@ component或者@ configuration一起使用。
@ bean显式声明了类与豆之间的对应关系,并且允许用户按照实际需要创建和配置豆实例。
该注解相当于:
<代码> & lt; bean id=皍seService"类=癱om.test.service.UserServiceImpl"/祝辞代码>
<>强普通组件强>
进口org.springframework.context.annotation.Bean; 进口org.springframework.context.annotation.Configuration; @ configuration 公开课MyConfigration { @ bean 公共用户用户(){ 返回新用户; } }
进口org.springframework.beans.factory.annotation.Autowired; 进口org.springframework.web.bind.annotation.GetMapping; 进口org.springframework.web.bind.annotation.RestController; @RestController 公开课用户控件{ @ autowired 用户用户; @GetMapping (“/test") 公共用户测试(){ 返回user.test (); } }
<>强命名组件强>
bean的命名为:用户,别名为:myUser,两个均可使用
进口org.springframework.context.annotation.Bean; 进口org.springframework.context.annotation.Configuration; @ configuration 公开课MyConfigration { @ bean (name=癿yUser") 公共用户用户(){ 返回新用户; } }
bean的命名为:用户,别名为:myUser/对于三个均可使用
进口org.springframework.context.annotation.Bean; 进口org.springframework.context.annotation.Configuration; @ configuration 公开课MyConfigration { @ bean (name={“myUser",“yourUser"}) 公共用户用户(){ 返回新用户; } }
<强>豆初始化和销毁
强>
公共类MyBean { 公共空间init () { System.out.println (“MyBean初始化…“); } 公共空间摧毁(){ System.out.println (“MyBean销毁…“); } 公共字符串get () { 返回“MyBean使用…“; } }
@ bean (initMethod=癷nit" destroyMethod=癲estroy") 公共MyBean MyBean () { 返回新MyBean (); }
<强>只能用@ bean不能使用@ component 强>
@ bean 公共>看完这篇关于如何配置和使用Spring @ bean注解的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。@ bean注如何配置和使用弹簧解