Spring uses javaconfig to implement the method and steps of configuration
•
Java
Do not use the XML configuration of spring, and leave it to java!
Javaconfig is a sub project of spring. After spring 4, 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; //说明这个类被Spring注册到了容器中 @Component public 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 + '\'' + '}'; } }
Profile:
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; //这个也会被spring容器托管,因为它本来就是一个@Component // @Configuration代表一个类,就和我们之前的ApplicationContext.xml是一样的 @Configuration @ComponentScan("com.lrx.poji") public class LiConfig { //注册一个bean,就相当于xml写的一个bean标签 //这个方法的名字就相当于bean标签中的ID属性 //方法的返回值相当于bean标签中的class属性 @Bean public User getUser(){ return new User(); //就是要注入到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) { //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器 // 然后通过配置类的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!
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码