前言
Spring是我们开发中的核心框架,传统的xml配置文件十分繁琐,所以在Spring2.5以后,程序员可以使用注解来配置依赖注入,而不是大量的在xml文件中配置,我们可以使用相关类、方法或字段的注解,将繁琐的xml配置移植到类本身。
方式一:半注解半xml配置文件实现依赖注入
首先,先来介绍一些必要的注解及其使用。
@Component
该注解使用于类上面,相当于配置文件中的:
<
bean
class=""/>
那么如何给bean的id赋值呢?我们不妨从@Component源代码中寻找答案
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
String value() default "";
}
可以看到,类中有一个value属性,而且默认为"",它就表示bean的id属性。当我们需要给bean赋id值的时候,我们通过在注解中给value赋值。比如:
@Component(value = “xxx”)
也可以这样写:
@Component(“xxx”)
@Component泛指各种组件,此注解还衍生出了三个和它一样的注解:
@Controller 一般用于表现层(web层)的注解
@Service 一般用于业务层(service层)的注解
@Repository 一般用于持久层(dao层)的注解
@Scope
@Scope注解的作用就是来调节对象的作用域。
此注解可以指定五种作用域
1. singleton单例模式(默认)
仅有一个该类的实例
2. prototype在这里插入代码片
原型模式
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
3. request
每一次http请求都会产生一个新的bean,作用域相当于servlet中的request作用域
4. session
每一次http请求都会产生一个新的bean,作用域相当于servlet中的session作用域
5. global session
在web中相当于session类型
举例
我们以学生和学校为例,先创建学校类School:
@Component("school")
public class School {
@Value("bju")
private String name