ioc注解开发

IOC 注解开发

示例

引入jar包: 除了要引入上述的四个包之外,还需要引入aop包。

创建 applicationContext.xml ,使用注解开发引入 context 约束(xsd-configuration.html)

<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 http://www.springframework.org/schema/beans/spring-beans.xsd

    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 

    <!-- bean definitions here -->

组件扫描: 使用IOC注解开发,需要配置组件扫描,也就是哪些包下的类使用IOC的注解。

<context:component-scan base-package=“demo1”>

在类上添加注解

使用注解设置属性的值

属性如果有set方法,将属性注入的注解添加到set方法

属性没有set方法,将注解添加到属性上。

@Component(“UserDao”)//相当于配置了一个 其id为UserDao,对应的类为该类

public class UserDAOImpl implements UserDAO {

@Override

public void save() {

// TODO Auto-generated method stub

System.out.println(“save”);

}

}

注解详解

@Component

组件注解,用于修饰一个类,将这个类交给 Spring 管理。

有三个衍生的注解,功能类似,也用来修饰类。

@Controller:修饰 web 层类

@Service:修饰 service 层类

@Repository:修饰 dao 层类

2.属性注入

普通属性使用 @Value 来设置属性的值

对象属性使用 @Autowired ,这个注解是按照类型来进行属性注入的。如果希望按照 bean 的名称或id进行属性注入,需要用 @Autowired 和 @Qualifier 一起使用

实际开发中,使用 @Resource(name=" ") 来进行按照对象的名称完成属性注入

3.其他注解

@PostConstruct 相当于 init-method,用于初始化函数的注解

@PreDestroy 相当于 destroy-method,用于销毁函数的注解

@Scope 作用范围的注解,常用的是默认单例,还有多例 @Scope(“prototype”)

IOC 的 XML 和注解开发比较

适用场景:XML 适用于任何场景;注解只适合自己写的类,不是自己提供的类无法添加注解。

可以使用 XML 管理 bean,使用注解来进行属性注入

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值