spring-3-基于注解的配置

参考什么是spring,它能够做什么?
参考w3cschool
参考Spring框架入门教程

1 基于注解的装配

在 Spring 中,尽管可以使用XML配置文件实现Bean的装配工作,但如果应用中Bean的数量较多,会导致XML配置文件过于臃肿,从而给维护和升级带来一定的困难。

Java从JDK 5.0以后,提供了Annotation(注解)功能,Spring 2.5版本开始也提供了对Annotation技术的全面支持,我们可以使用注解来配置依赖注入。

Spring默认不使用注解装配Bean,
因此需要在配置文件中添加<context:annotation-config/>,启用注解。

Spring中常用的注解如下。
1)@Component
可以使用此注解描述Spring中的Bean,但它是一个泛化的概念,仅仅表示一个组件(Bean),
并且可以作用在任何层次。使用时只需将该注解标注在相应类上即可。

2)@Repository
用于将数据访问层(DAO层)的类标识为Spring中的Bean,其功能与@Component相同。

3)@Service
通常作用在业务层(Service层),用于将业务层的类标识为Spring中的Bean,
其功能与@Component相同。

4)@Controller
通常作用在控制层(如Struts2的Action、SpringMVC的Controller),
用于将控制层的类标识为Spring中的Bean,其功能与@Component相同。

5)@Autowired
可以应用到Bean的属性变量、属性的setter方法、非setter方法及构造函数等,
配合对应的注解处理器完成Bean的自动配置工作。默认按照Bean的类型进行装配。

6)@Resource
作用与Autowired相同,区别在于@Autowired默认按照Bean类型装配,
而@Resource默认按照Bean实例名称进行装配。

@Resource中有两个重要属性:name和type。
Spring将name属性解析为Bean的实例名称,type属性解析为Bean的实例类型。
如果指定name属性,则按实例名称进行装配;
如果指定type属性,则按Bean类型进行装配。
如果都不指定,则先按Bean实例名称装配,如果不能匹配,则再按照Bean类型进行装配;
如果都无法匹配,则抛出NoSuchBeanDefinitionException异常。

7)@Qualifier
与@Autowired注解配合使用,会将默认的按Bean类型装配修改为按Bean的实例名称装配,
Bean的实例名称由@Qualifier注解的参数指定。

1.1 @Required注解

@Required注解应用于bean属性的setter方法,它表明受影响的bean属性在配置时必须放在XML 配置文件中,否则容器就会抛出一个BeanInitializationException异常。

1.1.1 文件Student.java

package net.biancheng;

import org.springframework.beans.factory.annotation.Required;
public class Student {
    private Integer age;
    private String name;
    @Required
    public void setAge(Integer age) {
        this.age = age;
    }
    public Integer getAge() {
        return age;
    }
    @Required
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

1.1.2 文件MainApp.java

package net.biancheng;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println("Name : " + student.getName() );
        System.out.println("Age : " + student.getAge() );
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皮皮冰燃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值