12.注解的使用.md

zhanglei 2022年05月30日 353次浏览

12.注解的使用

NewService类

package Spring5.Bean11;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class NewService {
    @Autowired//根据类型进行装配,不需要加入set方法,已封装
    @Qualifier("DaoImp1")//根据名称id导入
    private Dao dao;

    @Value("张磊")//替代property 注入普通类型属性
    private String name;
    public void show(){
        System.out.println("service......");
        dao.add();
        System.out.println(name);
    }
}

Dao接口

package Spring5.Bean11;

public interface Dao {
    public void add();
}

DaoImp实现类

package Spring5.Bean11;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

@Repository("DaoImp1")
public class DaoImp implements Dao{

    public void add(){
        System.out.println("add......");
    }
}

bean11.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:p="http://www.springframework.org/schema/p"
       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"
>
    <!--属性注入@AutoWired 根据属性类型注入
               @qualifier 根据属性名称注入要和@AutoWired一起使用
               @Resource(不属于Spring) 默认根据属性名称注入,也可根据属性类型注入
               @Value(value="") 替代property 注入普通类型属性
               见包Bean11-->

    <!--组件扫描-->
    <context:component-scan base-package="Spring5.Bean11"></context:component-scan>
</beans>

Test类

public class TEST {
   
    @Test
    public void testBean11(){
        ApplicationContext context=new ClassPathXmlApplicationContext("bean11.xml");
        NewService service = context.getBean("newService", NewService.class);
        service.show();
    }
}

测试结果

service......
add......
张磊