JavaConfig实现配置
前言:使用这个就不需要再去写配置文件了,直接全部使用注解来进行开发
先看一下整体的结构
TestConfig.java
package com.zkw.config;
import com.zkw.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
//@ComponentScan("com.zkw.pojo")
@Import(TestConfig2.class)
public class TestConfig {
@Bean
public User getUser(){
return new User();
}
}
@Configuration: 这个也会Spring容器托管,注册到容器中,因为它本身是一个@Component。另外 @Configuration 代表这是一个配置类,和我们之前所写的
ApplicationContext.xml
文件是一个东西。@Import(xxx.class) 这个就是把多个配置文件融合在一起。
@Bean:注册一个bean,就相当于
ApplicationContext.xml
文件中的一个bean标签,这个方法的名字getUser
就是bean标签中的 id,这个方法的返回值,就相当于bean标签中的class属性。注册bean还有一种方法以我的为例:
在
User.java
中使用@component这个注解让这个类被Spring容器托管,然后在TestConfig.java
配置类里边,使用@ComponentScan(“com.zkw.pojo”)扫描这个包,这个也可以实现bean的注册,只不过此时的id为user
User.java
package com.zkw.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//@Component
public class User {
@Value("Four Anger Man")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MyTest.java
import com.zkw.config.TestConfig;
import com.zkw.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
@Test
public void TestUser(){
//如果完全使用了配置类方式去做,我们只能通过AnnotationConfig 上下文来获取容器,通过配置类的Class来加载对象
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
User getUser = context.getBean("getUser", User.class);
System.out.println(getUser.getName());
}
}
结果如下