之前的学习中一直都在围绕Spring的xml配置文件进行bean的管理…Spring4之后Config成为了Spring的核心功能,可以完全脱离xml配置文件以零配置的形式实现。
其实说是零配置,只是xml不再需要;通过注解 + Java代码的形式取代xml。
@Configuration注解
配置注解:加在一个类上表明这个类与类名xml配置文件有同样的效果!
//ABCD.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
</beans>
@Configration
public class ABCD{
}
@ComponentScan注解
在没有完全脱离xml文件需要扫描注解时使用< context:component-scan / >扫描包下的所有注解,并且隐式的开启注解驱动支持。
组件扫描注解:加在使用了@Configration的类上,表名这个替代xml配置文件的工具类会进行扫描注解,等价于xml中的组件扫描标签
SpringUtil是一个代替xml的工具类,ComponentScan(“com.pojo”)扫描 "com.pojo"包下的所有注解。
@Configuration
@ComponentScan("com.pojo")
public class SpringUtil {
}
@Bean注解
Bean注解:用于创建bean对象,加在方法上;等价于xml中的< bean >标签,可以传入一些参数设置别名。
别名person,实体类是User。
@Bean("person")
public User getUser(){
return new User();
}
@Scope注解
Scope注解:bean对象作用域,虽然Bean注解中使用new关键字来创建对象,给人的感觉不像是从IOC容器中获取对象;但是底层还是受到Scope注解的约束。
@Scope("singleton") //单例,默认不写也是单例
@Scope("prototype") //原型模式,多例
public class User {
}
测试
使用上面的配置注解,在加上一些基本注解就能实现脱离xml配置文件
1. 编写实体类
@Component("user")
@Scope("singleton")
public class User {
@Value("薯条")
private String name;
public void speak(){
System.out.println(name + ": 说话!");
}
}
2. 编写配置工具
@Configuration
@ComponentScan("com.pojo")
public class SpringUtil {
@Bean("person")
public User getUser(){
return new User();
}
}
3. 测试
由于脱离了配置文件,无法使用ClassPathXmlApplicationContext加载,而由另外一个接口AnnotationConfigApplicationContext实现,传入工具类的class对象
public class SpringTest {
@Test
public void test1(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringUtil.class);
User user1 = context.getBean("person", User.class);
user1.speak();
User user2 = context.getBean("person", User.class);
System.out.println(user1.hashCode());
System.out.println(user2.hashCode());
}
}
总结
-
纯注解取代xml似乎看起来比较简单方便,实际上只是将配置文件中的标签零零散散的分布在各个类中,非常容易出现排错困难的情况,不推荐使用。
-
xml配置文件虽然繁琐,但是管理方便一目了然。对于一些复杂的配置实现轻松;例如:扫描包的时候不使用默认的方式,需要加上过滤器,这时候注解的方式就显得费力!
-
推荐xml与注解整合开发:使用xml管理Bean,注解完成属性注入。