纯注解使用@Bean维持依赖关系

@Bean: 之前将类注入到IOC容器里的注解(@Component @Repository @Service @Controller)只能作用在类上,所以不能使用在第三方类上。@Beanspring3之后出现的注解,作用在方法上,可以将一个方法的返回值作为bean对象存放在IOC容器里

思路:使用有参构造方式给属性赋值

方式一:直接调用已有方法

package com.ape.config;

import com.ape.controller.StudentController;
import com.ape.dao.StudentDao;
import com.ape.dao.StudentDaoImpl;
import com.ape.service.StudentService;
import com.ape.service.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;

@Configuration
// 注解扫描器
@ComponentScan(basePackages = "com.ape")
// 引入外部文件
@PropertySource(value = "classpath:message.properties")
// 引入外部配置类
@Import(ApplicationContextConfig2.class)
public class ApplicationContextConfig {
    /**
     * 方式一  直接调用方法,使用有参构造来保持依赖关系
     *
     * @return
     */
    @Bean
    public StudentDao dao(){
        return new StudentDaoImpl();
    }
    @Bean
    public StudentService service(){
        return new StudentServiceImpl(dao());
    }
    @Bean
    public StudentController controller(){
        return new StudentController(service());
    }
}

方式二:把IOC容器里的Bean对象拿出来注入到参数中,还是使用有参构造

package com.ape.config;

import com.ape.controller.StudentController;
import com.ape.dao.StudentDao;
import com.ape.dao.StudentDaoImpl;
import com.ape.service.StudentService;
import com.ape.service.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;

@Configuration
// 注解扫描器
@ComponentScan(basePackages = "com.ape")
// 引入外部文件
@PropertySource(value = "classpath:message.properties")
// 引入外部配置类
@Import(ApplicationContextConfig2.class)
public class ApplicationContextConfig {
    /**
     * 方式二,将已经注入IOC容器的对象拿出来作为参数
     * 使用有参构造保持依赖关系
     * 有没有@Autowired都可以
     *
     * @return
     */
    @Bean
    public StudentDao dao() {
        return new StudentDaoImpl();
    }

    @Bean
    public StudentService service(@Autowired StudentDao dao) {
        return new StudentServiceImpl(dao);
    }

    @Bean
    public StudentController controller(/*@Autowired*/ StudentService service) {
        return new StudentController(service);
    }
}
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值