4.使用注解创建对象

配置文件

<?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="day503FactoryBean"></context:component-scan>
</beans>

也可以通过配置类来代替

/**
 * @author wuyimin
 * @create 2021-05-03-22:21
 * @description 配置类
 */
@Configuration//作为配置类,代替xml配置文件
@ComponentScan(basePackages = {"day503FactoryBean"})
public class SpringConfig {

}

dao daoimpl service

public interface AnnoDao {
    public void add();
}

@Repository(value="DaoImpl1")
public class AnnoDaoImpl implements AnnoDao {
    @Override
    public void add() {
        System.out.println("add implements.....");
    }
}

@Repository(value="service")
public class AnnoService {
    //定义dao属性
    //不需要添加set方法
    //添加注入属性的注解
    @Autowired//根据类型进行注入
    @Qualifier(value = "DaoImpl1")//找到一个实现类
    private AnnoDao dao;//接口
    @Value(value = "abc")
    private String name;
    public void add(){
        System.out.println("service add...");
        dao.add();
    }
    public void show(){
        System.out.println(name);
    }
}

测试类:

public class annotationTest {
    //使用注解创建对象
    @Test
    public void test01(){
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("503bean7.xml");
        MyBean myBean=context.getBean("thisBean",MyBean.class);
        myBean.test();
    }
    //使用注解注入属性
    @Test
    public void test02(){
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("503bean7.xml");
        AnnoService myBean=context.getBean("service",AnnoService.class);
        myBean.add();
        myBean.show();
    }
    //完全注解--springboot
    @Test
    public void test03(){
        ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
        AnnoService myBean=context.getBean("service",AnnoService.class);
        myBean.add();
        myBean.show();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值