Spring基础学习3——spring IOC注解

Spring基础学习3——spring IOC注解

IOC:(Inverse of Control)spring的IoC容器是spring的核心,spring AOP是spring框架的重要组成部分。

(AOP)是以另一个角度来考虑程序结构,通过分析程序结构的关注点来完善面向对象编程(OOP)。OOP将应用程序分解成各个层次的对象,而AOP将程序分解成多个切面。spring AOP 只实现了方法级别的连接点,在J2EE应用中,AOP拦截到方法级别的操作就已经足够。在spring中,未来使IoC方便地使用健壮、灵活的企业服务,需要利用spring AOP实现为IoC和企业服务之间建立联系。

使用Sping的IOC对客户端DAO进行增强

使用方式:

// 在context中配置component要扫描的包的范围 
<context:component-scan base-package="com.hhh.spring.demo"></context:component-scan>


// 在我们对应的bean上配置@Compinent("取名"),这里等同于在context中创建bean的过程 
// <bean id="testIOCBean" class="com.hhh.spring.demo.bean.TestIOCBean"></bean>

@Component("testIOCBean")
public class TestIOCBean {
  public void  print(){
      System.out.print("TestIOCBean");
  }
}

// 使用,和普通的注入类似
ApplicationContext mApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
TestIOCBean mTestIOCBean = (TestIOCBean) mApplicationContext.getBean("testIOCBean");
mTestIOCBean.print();

@Component介绍

与Component类似功能的注解有三个:

@Controller:web层

@Service:service层

@Repository:dao层

// 可以直接替换
@Repository("testIOCBean")
public class TestIOCBean {
  public void  print(){
      System.out.print("TestIOCBean");
  }
}

属性的注入

@Value

设置普通属性

@Component("testIOCBean")
public class TestIOCBean {

    @Value("222222")
    private String name;

    public void  print(){
        System.out.print(name);
    }
}

@Autowired

设置对象类型的属性值。是按照类型注入的,名称无数所谓的

// 注入对象
@Component("testIOCBean")
public class TestIOCBean {
    @Value("222222")
    private String name;

    @Autowired
    private Car1Bean mCar1Bean;

    public void  print(){
        System.out.print(name +mCar1Bean.toString());
    }
}

@Qualifier

和@Autowired配合是用,注入对象。通过名字注入

@Autowired
@Qualifier(value = "car1bean")
private Car1Bean mCar1Bean;

@Resource

直接用名字进行对象注入

@Resource(name = "car1bean") // 这里的名字是xml中的名字
private Car1Bean mCar1Bean;

Bean生命周期相关注解

@PostConstruct   // 初始化 
public void  init(){
    System.out.print("init");
}

@PreDestroy // 销毁前
public  void  destroy(){
    System.out.print("destroy");
}

Bean的作用范围

@scope

  • singleton :默认单例

  • propotype :多例

  • request:

  • session:

  • globalsession:

@Service("customService")
@Scope("singleton")
public class CustomService {
...
}

xml和注解的比较

使用场景:

xml:可以使用任何场景

注解:有些地方用不了,这个类不是自己提供的(第三方的类)

 

常用方案:xml+ioc

xml管理bean,ioc完成属性注入

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值