使用java的方式配置Spring
实体类:
package com.ly.pojo; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; @Component public class User { private String name; public String getName() { return name; } @Value("凌云") public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
配置类:
package com.ly.config; import com.ly.pojo.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration //代表这是一个配置类,相当于beans.xml @ComponentScan("com.ly.pojo") public class lyconfig { @Bean //注册一个bean,相当于bean标签; //方法的名字相当于bean标签中的id属性 //这个方法的返回值,相当于bean标签中的class属性 public User user(){ return new User(); } }
测试类:
import com.ly.config.lyconfig; import com.ly.pojo.User; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MyTest { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(lyconfig.class); User getUser = context.getBean("user", User.class); System.out.println(getUser.getName()); } }
纯java的配置在Springboot非常常见!