This post is from my blog
The text before
I finally began to learn Spring, and the first content I came into contact with was beans. Therefore, I want to summarize what I have learned in two articles
The first chapter has two contents:
- The concept of JavaBean
- The Spring assembly Bean
The body of the
1. JavaBean concepts
What is a JavaBean
The word Bean is not a literal translation. Wikipedia explains the definition of a Bean:
JavaBeans are special classes in Java that encapsulate multiple objects into a bean. They are serializable, provide a no-argument constructor, and provide getters and setters to access properties of an object. The “Bean” in the name is the common name for a reusable software component for Java
Examples of Bean
- Create a Bean class
import java.io.Serializable; Public class UserBean implements Serializable {// Implements Serializable private String play; private Boolean isUser; // No argument constructor publicUserBean() {} / / routinesetGet operation public voidsetPlay(String play) { this.play = play; }
public String getPlay() { return play; }
public void setUser(Boolean user) { isUser = user; } // Getters for Boolean types have different names. Use is to better represent the type public BooleanisUser() { returnisUser; }}Copy the code
- Use the Bean class
Public class UserBeanTest {public static void main(String[] args){// Instantiate UserBean UserBean = new UserBean(); userBean.setPlay("I want to play");
userBean.setUser(true); // If it is the user, print the statementif(userBean.isUser()){ System.out.println(userBean.getPlay()); }}}Copy the code
To quote from Spring in Action:
In traditional Java applications, the bean life cycle is simple. The bean is instantiated using the Java keyword new, and the bean can then be used. Once the bean is no longer in use, it is automatically garbage collected by Java
2. Beans in Spring
In Spring, we configure and use beans to get the results we need
In the example above, if we were to create a Bean, we would use the keyword New. However, in Spring, the Bean creation is done by the Spring container, that is, the Bean is not created by the keyword New when used in Spring
Today we will focus on the assembly of a single Bean in Spring, only one Bean, and the next article will cover DI:
- Automatically.
- Assembly with XML
- Using Java assembly
1. Automatic assembly
To quote from Spring in Action: While you’ll find these display assembly techniques useful, Spring’s automated configuration is the most powerful in terms of convenience
We use a Demo for interpretation, first create two classes: the Student class and class StudentTest, and a spring configuration file – config. XML:
We need to write a configuration file that enables Component scanning to find classes with the @Component annotation, because I wrote a demo on Spring MVC, So a little explanation for the difference between @Component, @service, and @Controller:
@Component is a Component class that you use when you don’t know what it is, like this Demo where @Service says it’s a Component of the business layer and @Controller says it’s a Component of the control layer you can also use @Component in the business layer and the control layer, But this makes the code unreadable
Back to the configuration file:
This line:
<context:component-scan base-package="bean"/>
Copy the code
Indicates where Spring is scanning the component (package name) or, if base-package is not set, the package in which the configuration file is scanned
Then let’s look at the Student class:
This is just for testing purposes, so it’s greatly simplified, requiring only one console output statement
Because we configured Component scanning earlier, clicking on the flag next to it jumps to the Student class where we added the @Component annotation
All we need is a test. To test, we use Junit and import two JARS:
Junit 4.12. Jar hamcrest – all – 1.3. The jar
Step by step for the contents of the test file:
- @runwith: The execution class specified by this unit test (not yet well understood)
- @contextConfiguration: location of the configuration file, because I am using XML file for configuration, so enter the location of the configuration file
- Autowired: Automates Bean assembly. You can see here that the New keyword is not used, but the Bean is available at run time
- @test: Method to run a Test
You can see that the console outputs the statement from the Student class, proving that the assembly was successful
2. Use XML assembly
This article is about simple assembly, so much of the dependency injection approach will be skipped for the next article
So I’ll just show you how to create and assemble a Bean in an XML file
First we create a new configuration file, spring-bean.xml:
Create a Bean called “student” with the element. The class attribute specifies the type of the Bean
Then we modify the configuration information for the context in the test file:
We change the value of the @ContextConfiguration annotation to the configuration Bean file
Output result:
Proof of successful assembly
3. Use Java assembly
The use of Java as an assembly is highly recommended in Spring Field. I’m not used to writing configuration information in XML files.
We will create a class to hold Configuration information. We will add @Configuration to indicate that this is a Configuration class:
Next, we use an annotation in the configuration class: @bean:
We write a method in the configuration class that creates and returns the desired instance and adds @bean to the method, which is named as the Bean’s default name:
Studentconfig.class = studentConfig.class = studentConfig.class = studentConfig.class
Then the test results are obtained to prove the success of assembly:
The name of the method mentioned above is the default name of the Bean. Here’s a test:
Change the name of the method in the configuration class by adding a character “s” :
Then modify the test class. In this test, instead of creating an instance, we just test to see if we can find the Bean in context:
After testing, throw NoSuchBeanDefinitionException, said there was no found Bean named “student”
If I change the name of the method I just changed back, it will pass the test:
So much for assembling the most basic beans, the next article will cover all three in detail