springboot create the bean

There are two ways to create the bean springboot:

Annotated @ Component @ Controller @ Service 1. Direct class. . .

2. Use @Bean notes with @Configuration comment

The difference is:

@Configuration:
allowed to register additional bean or introduced in the context of other configuration class

This annotation is equivalent to an xml file.

Example 1: The following 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>

 

 In java configuration in probably the case.

@Configuration
public class JavaConfig{

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

@Bean:
role in the above method, the return value of the method can be generally injected into the container as a spring Bean.

Every bean has a name value in the Configuration inside, @ Bean's name is the method name, of course you can explicitly pointed out the bean name, and can have more than one name, as follows:

@Configuration
public class's JavaConfig {

@Bean ({ "the myUser", "User"})
public the User User () {
return new new the User ();
}
}
You can set the scope for the bean and the like, these properties requires certain annotations provided the following scope: it will no longer be a singleton

@Bean
@Scope (ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public the User User () {
return new new the User ();
}
@Component
Spring-loaded activated when bean.

Component and Controller and Service, etc. These annotations are no different, except Controller / Service is an agreement, where the agreement each with one.

Bean Component and then what difference does it make?

Component is a class annotation, Bean is a method comment.

Bean annotation also allows third-party packages as Bean, but Component is not it.
----------------
Disclaimer: This article is the original article CSDN bloggers' JAVA young woman ", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source and this link statement.
Original link: https: //blog.csdn.net/dmw412724/article/details/89237699

 

Guess you like

Origin www.cnblogs.com/anenyang/p/11912139.html