这两个代码(Spring Boot)有什么区别?

时间:2020-10-12 23:55:10

标签: spring-boot

这两个代码应该做完全相同的事情,但是第一个有效,而第二个无效。任何人都可以查看代码并提供有关为什么第二种方法失败的详细信息。

第一个代码:

@Component
public class AdminSqlUtil implements SqlUtil {
    
    @Autowired private ApplicationContext context;
    DataSource dataSource =(DataSource) context.getBean("adminDataSource");
    
    public void runSqlFile(String SQLFileName) {
        Resource resource = context.getResource(SQLFileName);
        EncodedResource encodedResource = new EncodedResource(resource, Charset.forName("UTF-8"));
        try {
            ScriptUtils.executeSqlScript(dataSource.getConnection(), encodedResource);
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        } 
    }

第二个代码:

@Component

public class AdminSqlUtil implements SqlUtil {
    
    @Autowired private ApplicationContext context;

    public void runSqlFile(String SQLFileName) {
        Resource resource = context.getResource(SQLFileName);
        EncodedResource encodedResource = new EncodedResource(resource, Charset.forName("UTF-8"));
        try {
            ScriptUtils.executeSqlScript((DataSource)context.getBean("adminDataSource").getConnection(), encodedResource);
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

1 个答案:

答案 0 :(得分:1)

第一个具有private范围,并且框架无法访问它。您可以在私有范围变量之前添加@inject,以便框架可以对其进行初始化。但是,最佳实践是定义一个公共依赖设置程序以使其起作用。

另一方面,第二个在开始时启动该值,顺便说一句,这不是依赖项注入。我不是在谈论好的和坏的做法。这是错误的。我们不会初始化假定由框架初始化的变量。

因此,让我们继续第一个吧,尝试为其添加一个setter

看看this link