前言
本文在配置Spring时完全使用Java中的注解,不是按前文所述使用Spring中有的注解方法进行注解开发,也不是按前文所述依据配置.xml文件进行开发。但是会将Java中注解的功能与XML配置文件中一些语句的功能做对比,帮助理解学习。
实现方法
下面将以一个实例,说明如何使用Java的方式配置Spring。
1.创建一个测试实体类User
创建一个测试实体类User,添加属性username。
需要用到的注解:
@Component:该注解放在需管理的实体类前,说明该类被Spring管理,相当于创建了一个bean。与.xml文件的实体类注解一致。
@Value(“属性值”):该注解放在属性名前或者该属性set方法前,用于属性值的注入。与.xml文件的实体类注解一致。
@Component
public class User {
private String username;
public String getUsername() {
return username;
}
@Value("属性值")
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
'}';
}
}
2. 创建配置类TestConfig
在该配置类中进行Spring配置。
其中注解的含义分别为:
@Configuration:写于类名前,说明该类是配置类。等同于.xml配置文件。
@ComponentScan(“包名”):扫描该包名下的文件,使得该包下的注解都生效。
@Import(TestConfig1.class):将其他文件的配置类导入该文件中。
@Bean:注解一个bean对象。等同于.xml中<bean></bean>
。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import java.security.PublicKey;
@Configuration
@ComponentScan("包名")
@Import(TestConfig1.class)
public class TestConfig {
@Bean // 等同于.xml中`<bean id="getUser" class="User"></bean>`
public User getUser(){ // 方法名 = id, 返回值 = class
return new User(); // return返回注入到bean中的对象
}
}
3. 测试
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
// ApplicationContext为容器接口,容器在初始化时先去读取配置类,可传多个配置类
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
User user = context.getBean("getUser", User.class);
System.out.println(user.toString());
}
}