spring IOC注解开发

1.引入aop包

2.xml文件中引入约束:

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

3.要在配置文件中配置包扫描

<context:component-scan base-package="xxx.xxx.xxx"/>

4.属性注入:

(1)可以不提供set方法,直接在属性名上添加@value("值") 

  (2)   如果提供了set方法,在set方法上添加@value("值") 

IOC注解详解

component

@Component  修改一个类,将这个类交给spring管理,相当于配置文件中配置<bean id="  "   class="   ">

为了更好分层,@Component衍生出三个注解,功能一样

@Controller   web层

@Service  service层

@Repository   dao层

属性注入

@Value  设置普通属性值

@Autowired   设置对象类型的属性值     根据类型来注入

@Qualified   和@Autowired配合使用  可以根据名称类型来注入

@Resource(name=“  ”)根据名称来注入

 

 

@PostConstruct   初始化方法      在对应的方法上面贴上标签

@PreDestory    销毁方法            在对应的方法上贴上标签

@scope  singleton  prototype       作用范围                  在类上贴

 

 

xml与注解配合开发   

不用再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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--<context:component-scan base-package="com.itlike"/>-->


    <context:annotation-config/>



    <bean id="person" class="com.itlike.demo1.Person"></bean>
</beans>

注意:在xml和注解结合开发时,不需要再扫描包,只需引入

     <context:annotation-config/>

说明让其使用注解来注入属性

如果是采用spring的单元测试   则不用  <context:annotation-config/>即可注入属性

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")

对应类:

package com.itlike.demo1;

import org.springframework.beans.factory.annotation.Value;

public class Person {
    @Value("abc")
    public String name;

}

测试类及结果

  public void test2(){
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        Person person =(Person) applicationContext.getBean("person");
        System.out.println(person.name);
    }
//abc

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值