omar
omar

Reputation: 41

what the difference between the two codes (Spring Boot)?

These two codes should do exactly the same thing, but the first one works and the second one doesnt work. Can anyone review the code and give the details about why the code failed during second approach.

The first code :

@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);
        } 
    }

The second code :

@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);
        }
    }

Upvotes: 1

Views: 122

Answers (1)

Iman Rosstin
Iman Rosstin

Reputation: 2355

The first one has a private scope and the framework can not access it. You could have add @inject before your private scope variable so the framework can initialize it. However the best practice is to define a public dependency setter for that to work.

The second one on the other hand initiates the value at the start, which is not a dependency injection by the way. I am not talking about good and bad practice. It is wrong. We don’t initialize a variable which is suppose to be initialized by the framework.

So lets go with the first one, Try to add a setter for it.

Take a look at this link.

Upvotes: 1

Related Questions