springboot创建bean

springboot创建bean的方式有两种:

1.直接类上加注解@Component@Controller@Service 。。。

2.使用@Bean注解配合@Configuration注解

区别是:

@Configuration:
允许在上下文中注册额外的bean或导入其他配置类

这个注解相当于一个xml文件.

举例1:如下的xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean class="com.User"></bean>
</beans>

 在java配置里大概就是这样。

@Configuration
public class JavaConfig{

@Bean
public User user(){
return new User();
}
}
 

扫描二维码关注公众号,回复: 7941246 查看本文章

@Bean:
作用在方法上面,通常可以将该方法的返回值作为Bean注入到spring的容器中.

每个bean都有一个name值,在Configuration里面,@Bean的name就是方法名.当然你可以显式地指出bean的name,并且可以拥有多个name,如下:

@Configuration
public class JavaConfig{

@Bean({"myUser","user"})
public User user(){
return new User();
}
}
你也可以为bean设置scope等,这些属性都需要一些特定的注解,如下设置scope:这将不再是个单例

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public User user(){
return new User();
}
@Component
spring启动的时候加载的bean.

Component和Controller以及Service等这些注解没有什么区别,只是Controller/Service是一种约定,约定分别加到哪一层。

那么Component和Bean又有什么区别呢?

Component是类注解,Bean是方法注解。

Bean注解还可以让第三方包作为Bean,但是Component则不行啦。
————————————————
版权声明:本文为CSDN博主「JAVA少妇」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/dmw412724/article/details/89237699

猜你喜欢

转载自www.cnblogs.com/anenyang/p/11912139.html