开发琐碎问题记录(1)

开发琐碎问题记录(1)

Springioc容器可以实例化抽象类吗?

当然是不可以的。

报错:Field blogService in com.kuangstudy.controller.BlogController required a bean of type ‘com.kuangstudy.service.blog.IBlogService’ that could not be found.

告诉你,我BlogController中需要一个bean类型是是IBlogService,但是在ioc容器中没有找到,说明。BlogServiceImpl 它没有ioc容器所加载

  • 原因:抽象类,不能实例化,不可能加入ioc容器
  • 因为ioc容器在管理这些对象,其实底层自动去调用这些类的无参构造函数。这个时候如果你是一个抽象类,根本就没办法实例化,所以抽象类不可能加载到IOC容器中
  • 在开发如果定义一个接口,或者抽象类,如果没有子类其实是没什么意义的,它们存在页只能在匿名内部类中发生效果。就是:lambda表达,函数式接口中存在意义。

为什么开发中要实现一个接口,这个接口会放入到ioc容器吗,springioc怎么处理这些对象和接口的关系的呢?

  • 在spring的开发中,接口其实是可以不用定义的,可以面向类编程,也可以面向接口编程。大部分的开发其实都是面向接口编程,方便后续的扩展,因为接口标准和规范的指定。
  • 如果你确定你开发中,未来都不会变更和扩展你的业务你用面向类编程有何不可能?未来很多业务其实暂时的不扩展,并不代表你未来不扩展,一旦扩展我们的接接口价值就体现出来了。
  • 是不会的,接口是不会实例化。那为什么注入的接口呢。因为如果你注入接口,springioc会把唯一的实现类,自动赋值给该接口实例。—多态
  • 如果一个接口有多子类,那怎么办,就报错,你需要指定选择那个子类进行实例。

springioc能够去注入静态成员吗?

springioc容器默认情况下是不能注入:static属性。

是否能通过一些方式或者机制让静态属性实例化呢?

通过set注入,或者构造函数注入给静态成员赋值

private static IBlogService blogService;

@Autowired
public void setBlogService(IBlogService blogService) {
    
    
    BlogController.blogService = blogService;
}

构造函数

   private static IBlogService blogService;

    @Autowired
    public BlogController(IBlogService blogService){
    
    
        BlogController.blogService = blogService;
    }

通过ioc的后置通知

  @Autowired
    private ApplicationContext context;
    
   
    @PostConstruct // 是构造函数执行之后执行的方法,一般用来做数据初始化.
    public void postcut(){
    
    
        BlogController.blogService = context.getBean(BlogServiceImpl.class);
    }

说明:这个只是一个面试题,在开发中,千万不要去写静态注入。

mybatis那个mapper接口为啥就可以没有实现类咧?

其实肯定是有的?底层是通过jdk的动态代理,产生了一个代理对象。

ibatis处理数据库curd=—SqlSession来处理

mybatis处理数据库curd=—Mapper动态代理来执行完成—底层-SqlSession来处理

@Configuration配置,明明是配置类的,为什么方法还要去增加@Bean。是什么呢?

现在配置注入bean的方式

package com.kuangstudy.config.mybatis;

import com.kuangstudy.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationContextConfiguration {
    
    
    
    
    @Bean
    public User getUser(){
    
    
        return new User();
    }
}

传统的方式:ApplicationContext.xml

<bean id="getUser" class="com.xxx.bean.User">
</bean>

配置类的出现其实就是解决传统的基于xml的方式的一致机制。

Guess you like

Origin blog.csdn.net/L_994572281_LYA/article/details/121897233