How to use JavaConfig to configure Spring
Editor to share with you how Spring uses JavaConfig to achieve configuration, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Do not use Spring's XML configuration, leave it to java!
JavaConfig is a subproject of Spring, and after Spring4, it is called the core function of Spring!
Entity class:
Package com.lrx.poji;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;// indicates that this class is registered by Spring in the container @ Componentpublic class User {@ Value ("lixin") private String name; public String getName () {return name;} public void setName (String name) {this.name = name;} @ Override public String toString () {return "User {" + "name='" + name +'\'+'}';}}
Configuration file:
Package com.lrx.config;import com.lrx.poji.User;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration / / this will also be hosted by the Spring container, because it is already a @ Component// @ Configuration representing a class, just like our previous ApplicationContext.xml, @ Configuration@ComponentScan ("com.lrx.poji") public class LiConfig {/ / register a bean It is equivalent to a bean tag written by xml / / the name of this method is equivalent to the return value of the ID attribute / / method in the bean tag is equivalent to the class attribute @ Bean public User getUser () {return new User () in the bean tag. / / is the object to be injected into bean}}
Test class:
Import com.lrx.config.LiConfig;import com.lrx.poji.User;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class MyTest {public static void main (String [] args) {/ / if we completely use the configuration class way to do it, we can only get the container / / through the AnnotationConfig context and load it through the class object of the configuration class! ApplicationContext context=new AnnotationConfigApplicationContext (LiConfig.class); User getUser= (User) context.getBean ("user"); System.out.println (getUser.getName ());}}
This pure Java configuration can be seen everywhere in Spring Boot!
These are all the contents of the article "how to configure Spring using JavaConfig". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!