VictorGram
VictorGram

Reputation: 2661

Spring boot: Convert class into bean

New to spring boot. I have a class that is implementing interface and I would like to convert this class into a bean. Is there a way to do it?

Here is the class:

public class UnitTestContextProvider implements MockDataProvider {

    @Override
    public MockResult[] execute(MockExecuteContext ctx) throws SQLException {

        // You might need a DSLContext to create org.jooq.Result and org.jooq.Record objects
        DSLContext create = DSL.using(SQLDialect.POSTGRES);
        MockResult[] mock = new MockResult[1];

        // The execute context contains SQL string(s), bind values, and other meta-data
        String sql = ctx.sql();

        // Exceptions are propagated through the JDBC and jOOQ APIs
        if (sql.toUpperCase().startsWith("DROP")) {
            throw new SQLException("Statement not supported: " + sql);
        }

        // You decide, whether any given statement returns results, and how many
        else if (sql.toUpperCase().startsWith("SELECT")) {

            // Always return one record
            Result<Record2<UUID, String>> result = create.newResult(CLIENT.CLIENT_ID, CLIENT.CLIENT_NAME);
            result.add(create
                    .newRecord(CLIENT.CLIENT_ID,CLIENT.CLIENT_NAME)
                    .values(UUID.fromString("88ccc2c2-492f-4f03-9676-3c39e0c51514"), "Orwell"));
            mock[0] = new MockResult(1, result);
        }

        // You can detect batch statements easily
        else if (ctx.batch()) {
            // [...]
        }

        return mock;
    }
}

And this is what I am trying:

 @Configuration
 public class ContextProviders{

    @Bean
    public UnitTestContextProvider unitTestContext() {
      //This is similar to the class described above.
    }
 }

My main confusion is how to handle the interface part.

Upvotes: 0

Views: 2286

Answers (1)

Tanmoy Majumdar
Tanmoy Majumdar

Reputation: 458

change your config to following. You need to annotate it with @Bean annotation. now you will be able to use @Autowired or @Inject annotation to inject it into another spring managed bean.

@Configuration
public class ContextProviders{
    @Bean
    public MockDataProvider unitTestContext() {
        return new UnitTestContextProvider();
    }
}

Upvotes: 4

Related Questions