Skip to content

Instantly share code, notes, and snippets.

@thiagolocatelli
Last active August 23, 2018 14:36
Show Gist options
  • Save thiagolocatelli/075a995c5d134338c6031ff6712ea9f7 to your computer and use it in GitHub Desktop.
Save thiagolocatelli/075a995c5d134338c6031ff6712ea9f7 to your computer and use it in GitHub Desktop.
example of java lib with isolated spring context
package com.example.customlib;
/**
*
* This class initializes annotations and beans for the Library.
*
*/
@ComponentScan("com.example.customlib")
@EnableAspectJAutoProxy
@EnableCaching
@EnableConfigurationProperties
public class AnnotationBuilder {
/**
* Bean creation for Sparta JdbcTemplate.
*
* @param dataSource for the connection
* @return new created bean
*/
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
/**
* Configuration Properties for custom object
*
*/
@Configuration
@ConfigurationProperties(prefix = "custom.property")
public static class CustomObject {
private Map < String, String > item = new HashMap < > ();
public Map < String, String > getItem() {
return item;
}
}
}
package com.example.customlib;
/**
*
* Entry-point for Custom Library.
*
*/
public class CustomLibraryAPI {
private ApplicationContext context;
private MyService myService;
/**
* Main configuration method for the API. Configures spring isolated context.
*
* @param dataSource DataSource
* @param properties Library properties
*/
public CustomLibraryAPI(DataSource dataSource, Properties properties) {
final Map < String, Object > extraParams = new HashMap < String, Object > ();
extraParams.put("dataSource", dataSource);
context = SpringContextUtils.contextMergedBeans(extraParams, AnnotationBuilder.class, properties);
myService = context.getBean(MyService.class);
}
// make any spring bean from the isolated context available through getters.
}
/*
* Initiate the library inside your micronaut
*/
@Factory
class CustomLibraryFactory {
@Bean
@Singleton
CustomLibraryAPI customLibraryAPI(Datasource datasource, Properties properties) {
return new CustomLibraryAPI(datasource, properties);
}
}
package com.example.customlib.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class MyRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
}
package com.example.customlib.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired
private CustomObject customObject;
@Autowired
private MyRepository myRepository;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment