Spring-02(使用JavaConfig进行配置)
使用JavaConfig进行配置
①写一个实体类
package pojo; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; public class User { @Value("xcy") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
②定义一个JavaConfig类,在类上使用@Configuration 注解,将会使当前类作为一个 Spring 的容器来使用,用于完成 Bean 的创建。在该 JavaConfig 的方法上使用@Bean,将会使一个普通方法所返回的结果变为指定名称的 Bean 实例。
package config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import pojo.User; @Configuration public class Myconfig { @Bean public User getUser(){ return new User(); } }
进行这个代码后,相当于创建了一个 id=“getUser”的bean对象。也可以在bean后面添加名字比如@Bean("user")相当于创建了一个id=“user”的bean对象。
③进行测试
import config.Myconfig; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import pojo.User; public class MyTest { public static void main(String[] args) { /* 注意之前是 ApplicationContext Context = new ClassPathXmlApplicationContext("applicationContext.xml"); 后面是ClassPathXmlApplicationContext,现在javaconfig配置文件后面是AnnotationConfigApplicationContext 且之前后面跟的是xml文件名,而用JavaConfig进行配置后面跟的是配置类。 */ ApplicationContext Context = new AnnotationConfigApplicationContext(Myconfig.class); User getUser = Context.getBean("getUser", User.class); System.out.println(getUser.getName()); } }