搜索热词
不使用Spring的XML配置,全权交给java来做!
JavaConfig是Spring的一个子项目,在Spring4之后,它称为了Spring的核心功能!
实体类:
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 + '\'' +
'}';
}
}
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的对象
}
}
测试类:
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());
}
}
这种纯Java的配置方式在Spring Boot中随处可见!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
相关文章
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250