AspectJ not executing on Junit methods - spring-boot

Using AOP, I am trying to log test method execution time, but nothing happens when I run a test method.
I've tried to change regex in my pointcut but doesen't seem to be working.
My aspect class:
#Aspect
#Component
public class LoggableAspect {
#Pointcut("execution(public * com.mozzartbet.*.*.*Test.*(..))")
public void publicTestMethod() {}
#Around("publicTestMethod() && #annotation(loggable)")
public Object logTestExecutionTime(ProceedingJoinPoint joinPoint, Loggable loggable) throws Throwable {
long t1 = System.currentTimeMillis();
Logger logger = LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName());
StringBuilder prefix = new StringBuilder(joinPoint.getSignature().getName()).append("()");
Object result = null;
try {
if (loggable.detail()) {
prefix.append(": ").append(Joiner.on(",").join(joinPoint.getArgs()));
}
result = joinPoint.proceed();
return result;
} finally {
long t2 = System.currentTimeMillis();
if (loggable.detail()) {
prefix.append(" -> ").append(result);
}
logger.info("{} took {} ms", prefix, t2 - t1);
}
}
}
My test class:
package com.mozzartbet.gameservice.services.impl;
public class PlayerServiceImplTest extends BaseServiceTest {
#Autowired
private PlayerService playerService;
#Test
#Loggable(detail = true)
public void testInsert() {
assertThat(playerService.insert(Player.builder().id("foo").build()), is(1));
}
}
Annotation:
#Retention(RUNTIME)
#Target(METHOD)
public #interface Loggable {
boolean detail() default false;
}
PlayerService insert method
#Override
public int insert(Player player) {
try {
return playerDao.insert(player);
} catch (DuplicateKeyException e) {
throw new PlayerException(PlayerExceptionCode.DUPLICATED_PLAYER_ID, "ID: %s is duplicated!", player.getId());
}
}
Dao insert method:
#Override
public int insert(Player player) {
return playerMapper.insert(player);
}
I am inserting with mybatis.

Your #annotation definition is incorrect.
You should specify the qualified package name of annotation.
#Around("publicTestMethod() && #annotation(your_package.Loggable)")

Related

Register DynamicParameterizedType global

How can i register a global available DynamicParameterizedType in hibernate?
I wrote the following type:
public class QuantityType extends AbstractSingleColumnStandardBasicType<Quantity<?>> implements DynamicParameterizedType {
public static final QuantityType INSTANCE = new QuantityType();
public QuantityType() {
super(DoubleTypeDescriptor.INSTANCE, new QuantityJavaDescriptor(AbstractUnit.ONE));
}
#Override
public String getName() {
return QuantityType.class.getSimpleName();
}
#Override
public void setParameterValues(Properties parameters) {
ParameterType reader = (ParameterType) parameters.get(PARAMETER_TYPE);
if (reader == null) throw new RuntimeException("Not Implemented");
Unit<?> resolvedUnit = resolveUnit(reader);
setJavaTypeDescriptor(new QuantityJavaDescriptor(resolvedUnit));
}
private Unit<?> resolveUnit(ParameterType reader) {...}
}
and registered it with a service registration in hibernate:
public class QuantityTypeRegistration implements TypeContributor {
#Override
public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
typeContributions.contributeType(QuantityType.INSTANCE);
}
}
If i use the type in an entity, the wrap/unwrap method of the JavaTypeDescriptor gets called,
but instead of the parameterized JavaTypeDescriptor, the default JavaTypeDescriptor gets called. For some reason the setParameterValues method was not called.
Code: https://github.com/raynigon/unit-api/tree/master/jpa-starter/src/main/java/com/raynigon/unit_api/jpa

Infinispan + Spring Boot - Doesn't Cache

Trying to Implement infinispan base cache on spring boot using custom annotation:
#Aspect
#Configuration
#Slf4j
public class CacheAnnotationAspect {
Logger logger = LoggerFactory.getLogger(CacheAnnotationAspect.class);
#Autowired
InfinispanCacheService cacheService;
#Around("#annotation(com.calsoft.lib.cache.CacheResult)")
public Object cacheResult(ProceedingJoinPoint joinPoint)throws Throwable{
logger.info("Cache Operation :: CacheResult annotation advice invoked...");
CacheResult cacheResult=(CacheResult) getAnnotation(joinPoint,CacheResult.class);
CacheConfig cacheConfig=CacheConfig.from(cacheResult);
Object resultFromCache=getFromCache(joinPoint,cacheConfig);
if(resultFromCache!= null){
return resultFromCache;
}
Object result=joinPoint.proceed(joinPoint.getArgs());
storeInCache(result,joinPoint,cacheConfig);
return result;
}
private void storeInCache(Object result, ProceedingJoinPoint joinPoint, CacheConfig cacheConfig) {
if(result==null){
log.info("Cache op :: null values not cached");
return;
}
CacheService cacheService=getCacheService();
if(cacheService==null){
logger.info("Cache op :: CacheGet Failed : No CacheService available for use..");
}
DefaultCacheKey defaultCacheKey=getKey(joinPoint,cacheConfig);
String cacheName=getCacheName(cacheConfig.getCacheName(),joinPoint);
long lifeSpan=cacheConfig.getLifespan();
if(lifeSpan== CommonConstant.CACHE_DEFAULT_LIFE){
cacheService.put(cacheName,defaultCacheKey,result);
}else{
cacheService.put(cacheName,defaultCacheKey,result,lifeSpan,cacheConfig.getUnit());
}
logger.info("Cache Op :: Result cached :: {} ",cacheConfig);
}
private DefaultCacheKey getKey(ProceedingJoinPoint joinPoint, CacheConfig cacheConfig) {
List<Object> keys=new ArrayList<>();
Object target=joinPoint.getTarget();
MethodSignature methodSignature=MethodSignature.class.cast(joinPoint.getSignature());
Method method=methodSignature.getMethod();
Annotation[][] parameterAnnotations=method.getParameterAnnotations();
if(isEmpty(trim(cacheConfig.getKeyPrefix()))){
keys.add(target.getClass().getName());
keys.add(method.getName());
}else{
keys.add(cacheConfig.getKeyPrefix());
}
if(isCacheKeySpecified(parameterAnnotations)){
keys.addAll(getCacheKeys(joinPoint,parameterAnnotations));
}else{
keys.addAll(Arrays.asList(joinPoint.getArgs()));
}
return new DefaultCacheKey(keys.toArray());
}
private Collection<?> getCacheKeys(ProceedingJoinPoint joinPoint, Annotation[][] parameterAnnotations) {
Object[] args=joinPoint.getArgs();
List<Object> result=new ArrayList<>();
int i=0;
for(Annotation[] annotations: parameterAnnotations){
for(Annotation annotation: annotations){
if(annotation instanceof CacheKey){
result.add(args[i]);
break;
}
}
i++;
}
return result;
}
private boolean isCacheKeySpecified(Annotation[][] parameterAnnotations) {
for(Annotation[] annotations:parameterAnnotations){
for(Annotation annotation:annotations){
if(annotation instanceof CacheKey) {
return true;
}
}
}
return false;
}
private Object getFromCache(ProceedingJoinPoint joinPoint, CacheConfig cacheConfig) {
CacheService cacheService = getCacheService();
if (cacheService == null) {
logger.info("Cache op :: CacheGet Failed : No CacheService available for use..");
}
String cacheName=getCacheName(cacheConfig.getCacheName(),joinPoint);
DefaultCacheKey defaultCacheKey=getKey(joinPoint,cacheConfig);
return cacheService.get(cacheName,defaultCacheKey);
}
private String getCacheName(String cacheName, ProceedingJoinPoint joinPoint) {
boolean nameNotDefined=isEmpty(trim(cacheName));
if(nameNotDefined){
logger.error("Cache op :: Cache Name not defined");
}else{
CacheService cacheService=getCacheService();
if(!cacheService.cacheExists(cacheName)){
throw new RuntimeException("Cache with the name "+ cacheName+" does not exists");
}
}
return cacheName;
}
private CacheService getCacheService() {
return cacheService;
}
private Annotation getAnnotation(ProceedingJoinPoint joinPoint, Class type) {
MethodSignature methodSignature=MethodSignature.class.cast(joinPoint.getSignature());
Method method=methodSignature.getMethod();
return method.getAnnotation(type);
}
}
Above class << CacheAnnotationAspect >> is custom annotation #CacheResult Aspect implementation where it will first try to retrieve from cache and if not found will make actual dao call and then store in cache.
Below is the of the implementation of InfinispanCacheService which invokes cachemager to get/put cache entries.
#Service
public class InfinispanCacheService implements CacheService {
Logger logger = LoggerFactory.getLogger(InfinispanCacheService.class);
#Autowired
private DefaultCacheManagerWrapper cacheManagerWrapper;
private DefaultCacheManager infiniCacheManager;
private DefaultCacheManager initializeCacheManager(){
if(infiniCacheManager==null){
infiniCacheManager=cacheManagerWrapper.getCacheManager();
}
return infiniCacheManager;
}
#PostConstruct
public void start(){
logger.info("Initializing...InifinispanCacheService ....");
initializeCacheManager();
for(String cacheName : infiniCacheManager.getCacheNames()){
infiniCacheManager.startCache(cacheName);
}
}
#Override
public Object get(String cacheName, Object key) {
return getCache(cacheName).get(key);
}
#Override
public void put(String cacheName, Object key, Object value, long lifespan, TimeUnit unit) {
Cache cache=getCache(cacheName);
cache.put(key,value,lifespan,unit);
}
#Override
public void put(String cacheName, Object key, Object value) {
Cache cache=getCache(cacheName);
cache.put(key,value);
}
private Cache<Object,Object> getCache(String cacheName) {
Cache<Object,Object> cache;
if(isEmpty(trim(cacheName))){
cache=infiniCacheManager.getCache();
}else{
cache=infiniCacheManager.getCache(cacheName,false);
}
return cache;
}
#Override
public boolean cacheExists(String cacheName) {
return infiniCacheManager.cacheExists(cacheName);
}
}
<<<<<< The DefaultCacheManager below is one which during startup initializes the DefaultCacheManager by loading the infispan.xml configuration >>>>>
#Component
public class DefaultCacheManagerWrapper {
Logger logger = LoggerFactory.getLogger(DefaultCacheManagerWrapper.class);
// #Value("${classpath:spring.cache.infinispan.config}")
private String fileName="file:\\calsoft\\devlabs\\ecom2\\ecom-svc-admin\\src\\main\\resources\\infinispan.xml";
private DefaultCacheManager infiniCacheManager;
#PostConstruct
public void start(){
logger.info(" Received File Name :: {} ",fileName);
try{
URL fileUrl=new URL(fileName);
URLConnection urlConnection=fileUrl.openConnection();
InputStream inputStream=urlConnection.getInputStream();
infiniCacheManager=new DefaultCacheManager(inputStream);
infiniCacheManager.start();
logger.info("Cache Manager Initialized....");
}catch(MalformedURLException mue){
logger.error("Error creating file url ",mue.getMessage());
} catch (IOException e) {
logger.error("Error creating file url ",e.getMessage());
}
}
public void stop() { infiniCacheManager.stop();}
public DefaultCacheManager getCacheManager(){
return infiniCacheManager;
}
}
<<<< Infinispan.xml configuration >>
<?xml version="1.0" encoding="UTF-8"?>
<infinispan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:scehmaLocation="
urn:infinispan:config:7.2
http://www.infinispan.org/schemas/infinispan-config-7.2.xsd"
xmlns="urn:infinispan:config:7.2">
<cache-container default-cache="attributeset-cache">
<!-- template configurations -->
<local-cache-configuration name="local-template">
<expiration interval="10000" lifespan="50000" max-idle="50000"/>
</local-cache-configuration>
<!-- cache definitions -->
<local-cache name="attributeset-cache" configuration="local-template"/>
</cache-container>
</infinispan>
Annotation at controller level:
#CacheResult(cacheName= CommonConstant.ATTRIBUTE_SET_CACHE,lifespan=10,unit = TimeUnit.MINUTES)
#GetMapping("/eavattributeset")
public List<EavAttributeSet> fetchAllAttributes() {
return eavAttributeService.fetchAllEavattributesets();
}
<< EavAttributeService >>
#Service
public class EavAttributeService {
Logger logger = LoggerFactory.getLogger(EavAttributeService.class);
#Autowired
private EavAttributeJpaRepository eavAttributeJpaRepository;
#Autowired
EavAttributeSetJpaRepository eavAttributeSetJpaRepository;
public List<EavAttributeSet> fetchAllEavattributesets() {
return eavAttributeSetJpaRepository.findAll();
}
}
<< CacheConfig >>
#Data
#Slf4j
#AllArgsConstructor
#NoArgsConstructor
public class CacheConfig {
private String cacheName;
private long lifespan;
private TimeUnit unit;
private String keyPrefix;
public static CacheConfig from(CacheResult cacheResult) {
return new CacheConfig(cacheResult.cacheName(), cacheResult.lifespan(), cacheResult.unit(), cacheResult.keyPrefix());
}
}
Issue : The data is not getting cache, Wherever #CacheResult annotation is used the CacheAnnotationAspect is getting invoked and the check for data also happens in cache but when it tries to store the data in cache it does not cache and every subsequent call of this method does not return any data.
It works fine when i try with below configuration on infinispan.xml.
<expiration lifespan="50000"/>
Can you try with the above config and see if it using the cached data.
I guess it could be the max-idle timeout (10 milliseconds) which could be issue.

#RefreshScope annotated Bean registered through BeanDefinitionRegistryPostProcessor not getting refreshed on Cloud Config changes

I've a BeanDefinitionRegistryPostProcessor class that registers beans dynamically. Sometimes, the beans being registered have the Spring Cloud annotation #RefreshScope.
However, when the cloud configuration Environment is changed, such beans are not being refreshed. Upon debugging, the appropriate application events are triggered, however, the dynamic beans don't get reinstantiated. Need some help around this. Below is my code:
TestDynaProps:
public class TestDynaProps {
private String prop;
private String value;
public String getProp() {
return prop;
}
public void setProp(String prop) {
this.prop = prop;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("TestDynaProps [prop=").append(prop).append(", value=").append(value).append("]");
return builder.toString();
}
}
TestDynaPropConsumer:
#RefreshScope
public class TestDynaPropConsumer {
private TestDynaProps props;
public void setProps(TestDynaProps props) {
this.props = props;
}
#PostConstruct
public void init() {
System.out.println("Init props : " + props);
}
public String getVal() {
return props.getValue();
}
}
BeanDefinitionRegistryPostProcessor:
public class PropertyBasedDynamicBeanDefinitionRegistrar implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {
private ConfigurableEnvironment environment;
private final Class<?> propertyConfigurationClass;
private final String propertyBeanNamePrefix;
private final String propertyKeysPropertyName;
private Class<?> propertyConsumerBean;
private String consumerBeanNamePrefix;
private List<String> dynaBeans;
public PropertyBasedDynamicBeanDefinitionRegistrar(Class<?> propertyConfigurationClass,
String propertyBeanNamePrefix, String propertyKeysPropertyName) {
this.propertyConfigurationClass = propertyConfigurationClass;
this.propertyBeanNamePrefix = propertyBeanNamePrefix;
this.propertyKeysPropertyName = propertyKeysPropertyName;
dynaBeans = new ArrayList<>();
}
public void setPropertyConsumerBean(Class<?> propertyConsumerBean, String consumerBeanNamePrefix) {
this.propertyConsumerBean = propertyConsumerBean;
this.consumerBeanNamePrefix = consumerBeanNamePrefix;
}
#Override
public void setEnvironment(Environment environment) {
this.environment = (ConfigurableEnvironment) environment;
}
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
}
#Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefRegistry) throws BeansException {
if (environment == null) {
throw new BeanCreationException("Environment must be set to initialize dyna bean");
}
String[] keys = getPropertyKeys();
Map<String, String> propertyKeyBeanNameMapping = new HashMap<>();
for (String k : keys) {
String trimmedKey = k.trim();
String propBeanName = getPropertyBeanName(trimmedKey);
registerPropertyBean(beanDefRegistry, trimmedKey, propBeanName);
propertyKeyBeanNameMapping.put(trimmedKey, propBeanName);
}
if (propertyConsumerBean != null) {
String beanPropertyFieldName = getConsumerBeanPropertyVariable();
for (Map.Entry<String, String> prop : propertyKeyBeanNameMapping.entrySet()) {
registerConsumerBean(beanDefRegistry, prop.getKey(), prop.getValue(), beanPropertyFieldName);
}
}
}
private void registerConsumerBean(BeanDefinitionRegistry beanDefRegistry, String trimmedKey, String propBeanName, String beanPropertyFieldName) {
String consumerBeanName = getConsumerBeanName(trimmedKey);
AbstractBeanDefinition consumerDefinition = preparePropertyConsumerBeanDefinition(propBeanName, beanPropertyFieldName);
beanDefRegistry.registerBeanDefinition(consumerBeanName, consumerDefinition);
dynaBeans.add(consumerBeanName);
}
private void registerPropertyBean(BeanDefinitionRegistry beanDefRegistry, String trimmedKey, String propBeanName) {
AbstractBeanDefinition propertyBeanDefinition = preparePropertyBeanDefinition(trimmedKey);
beanDefRegistry.registerBeanDefinition(propBeanName, propertyBeanDefinition);
dynaBeans.add(propBeanName);
}
private String getConsumerBeanPropertyVariable() throws IllegalArgumentException {
Field[] beanFields = propertyConsumerBean.getDeclaredFields();
for (Field bField : beanFields) {
if (bField.getType().equals(propertyConfigurationClass)) {
return bField.getName();
}
}
throw new BeanCreationException(String.format("Could not find property of type %s in bean class %s",
propertyConfigurationClass.getName(), propertyConsumerBean.getName()));
}
private AbstractBeanDefinition preparePropertyBeanDefinition(String trimmedKey) {
BeanDefinitionBuilder bdb = BeanDefinitionBuilder.genericBeanDefinition(PropertiesConfigurationFactory.class);
bdb.addConstructorArgValue(propertyConfigurationClass);
bdb.addPropertyValue("propertySources", environment.getPropertySources());
bdb.addPropertyValue("conversionService", environment.getConversionService());
bdb.addPropertyValue("targetName", trimmedKey);
return bdb.getBeanDefinition();
}
private AbstractBeanDefinition preparePropertyConsumerBeanDefinition(String propBeanName, String beanPropertyFieldName) {
BeanDefinitionBuilder bdb = BeanDefinitionBuilder.genericBeanDefinition(propertyConsumerBean);
bdb.addPropertyReference(beanPropertyFieldName, propBeanName);
return bdb.getBeanDefinition();
}
private String getPropertyBeanName(String trimmedKey) {
return propertyBeanNamePrefix + trimmedKey.substring(0, 1).toUpperCase() + trimmedKey.substring(1);
}
private String getConsumerBeanName(String trimmedKey) {
return consumerBeanNamePrefix + trimmedKey.substring(0, 1).toUpperCase() + trimmedKey.substring(1);
}
private String[] getPropertyKeys() {
String keysProp = environment.getProperty(propertyKeysPropertyName);
return keysProp.split(",");
}
The Config class:
#Configuration
public class DynaPropsConfig {
#Bean
public PropertyBasedDynamicBeanDefinitionRegistrar dynaRegistrar() {
PropertyBasedDynamicBeanDefinitionRegistrar registrar = new PropertyBasedDynamicBeanDefinitionRegistrar(TestDynaProps.class, "testDynaProp", "dyna.props");
registrar.setPropertyConsumerBean(TestDynaPropConsumer.class, "testDynaPropsConsumer");
return registrar;
}
}
Application.java
#SpringBootApplication
#EnableDiscoveryClient
#EnableScheduling
public class Application extends SpringBootServletInitializer {
private static Class<Application> applicationClass = Application.class;
public static void main(String[] args) {
SpringApplication sa = new SpringApplication(applicationClass);
sa.run(args);
}
}
And, my bootstrap.properties:
spring.cloud.consul.enabled=true
spring.cloud.consul.config.enabled=true
spring.cloud.consul.config.format=PROPERTIES
spring.cloud.consul.config.watch.delay=15000
spring.cloud.discovery.client.health-indicator.enabled=false
spring.cloud.discovery.client.composite-indicator.enabled=false
application.properties
dyna.props=d1,d2
d1.prop=d1prop
d1.value=d1value
d2.prop=d2prop
d2.value=d2value
Here are some guesses:
1) Perhaps the #RefreshScope metadata is not being passed to your metadata for the bean definition. Call setScope()?
2) The RefreshScope is actually implemented by https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/refresh/RefreshScope.java, which itself implements BeanDefinitionRegistryPostProcessor. Perhaps the ordering of these two post processors is issue.
Just guesses.
We finally resolved this by appending the #RefreshScope annotation on the proposed dynamic bean classes using ByteBuddy and then, adding them to Spring Context using Bean Definition Post Processor.
The Post Processor is added to spring.factories so that it loads before any other dynamic bean dependent beans.

Spring + Hibernate + TestNG + Mocking nothing persist, nothing is readed in test

Fighting with TestNG, Spring an Hibernate. I'm writing test for Service class, and it's always failure. But without test class works fine. So App is working, but tests don't want to.
Here is my test class
#Transactional
public class BorrowerServiceTest {
#Mock
BorrowerDAOImpl borrowerDAO;
#InjectMocks
BorrowerService borrowerService;
#BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void persistTest() {
Borrower borrower = new Borrower.BorrowerBuilder().firstName("Lars").lastName("Urlich").adress("LA")
.phoneNumber("900900990").build();
borrowerService.persist(borrower);
List<Borrower> borrowerList = borrowerService.getBorrowerByName("Lars Urlich");
Assert.assertEquals(true, borrower.equals(borrowerList.get(0)));
}
}
My BorrowerService:
#Service("borrowerService")
#Transactional
public class BorrowerService {
#Autowired
private BorrowerDAO borrowerDAO;
public List<Borrower> getBorrowers() {
return borrowerDAO.getBorrowers();
}
public List<Borrower> getBorrowerByName(String name) {
return borrowerDAO.getBorrowerByName(name);
}
public boolean removeBorrower(Borrower borrower) {
return borrowerDAO.removeBorrower(borrower);
}
public boolean persist(Borrower borrower) {
return borrowerDAO.persist(borrower);
}
}
My BorrowerDAOImpl:
#Repository("borrowerDAO")
#Transactional
public class BorrowerDAOImpl extends DAO implements BorrowerDAO {
#Override
public List<Borrower> getBorrowers() {
List<Borrower> borrowerList = null;
Query query = entityManager.createQuery("SELECT B FROM Borrower B");
borrowerList = query.getResultList();
return borrowerList;
}
#Override
public List<Borrower> getBorrowerByName(String name) {
List<Borrower> borrowerList = null;
String[] values = name.split(" ");
Query query = entityManager.createQuery("SELECT B FROM Borrower B WHERE B.firstName LIKE '" + values[0]
+ "' AND B.lastName LIKE '" + values[1] + "'");
borrowerList = query.getResultList();
return borrowerList;
}
#Override
public boolean removeBorrower(Borrower borrower) {
String firstName = borrower.getFirstName();
String lastName = borrower.getLastName();
Query query = entityManager
.createQuery("DELETE Borrower where FIRST_NAME LIKE :FirstName AND LAST_NAME LIKE :LastName");
query.setParameter("FirstName", firstName);
query.setParameter("LastName", lastName);
query.executeUpdate();
return true;
}
#Override
public boolean persist(Borrower borrower) {
entityManager.persist(borrower);
return true;
}
}
and abstract DAO:
#Repository
#Transactional
public abstract class DAO {
#PersistenceContext
protected EntityManager entityManager;
}
Maven returns failure:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
at java.util.LinkedList.get(LinkedList.java:476)
at com.me.service.test.BorrowerServiceTest.persistTest(BorrowerServiceTest.java:41)
I also had to fight with this. The problem here is that your test runs in it's own transaction, so nothing will be committed during method's execution. Now here is what I did:
public class IntegrationTest extends SomeTestBase
{
#Autowired
private PlatformTransactionManager platformTransactionManager;
private TransactionTemplate transactionTemplate;
#Autowired
private BeanToTest beanToTest;
#Override
#Before
public void setup()
{
super.setup();
this.transactionTemplate = new TransactionTemplate(this.platformTransactionManager);
}
#Test
public void fooTest()
{
// given
// when
boolean result = this.transactionTemplate.execute(new TransactionCallback<Boolean>()
{
#Override
public Boolean doInTransaction(TransactionStatus status)
{
return IntegrationTest.this.beanToTest.foo();
}
});
// then
}
}
This allows you to have methods execute within a separate transaction. Please note that you might declare some variables as final.
Hope that helps.
Check the Spring documentation: it looks your test class should extend AbstractTestNGSpringContextTests.
Use #Commit annotation on the whole test class or even method to persist changes made in the test. For more information https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#commit

Use #Autowired in #Webservice (other solutions found did not work)

We are trying to use autowiring in our webservice, but this doens't seem to work (generates nullPointer). We have been searching for a solution for quite a long time, but did not succeed.
Our webservice:
#WebService(wsdlLocation = "/WEB-INF/wsdl/contract.wsdl", serviceName = "BookingService", targetNamespace = "http://realdolmen.com/", portName = "BookingServicePortType")
public class BookingService extends SpringBeanAutowiringSupport implements BookingServicePortType {
#Autowired
BookingServiceBean bookingServiceBean;
#Autowired
TariffService tariffService;
#Override
public BookingResponse createBooking(#WebParam(name = "bookingInput", targetNamespace = "http://realdolmen.com/", partName = "tariffId") BookingInput input) {
Tariff tariff = tariffService.getTariffById(input.getTariffId());
Booking booking = new Booking.BookingBuilder().withBaggageAllowance(tariff.getFlight().getBaggageAllowance())
.withDayOfDeparture(input.getDayOfDeparture()).withHourOfDeparture(input.getHourOfDeparture()).withTariff(tariff).withDuration(input.getDuration()).createBooking();
bookingServiceBean.createBooking(booking);
BookingResponse bookingResponse = new BookingResponse();
bookingResponse.setBookingId(booking.getId());
bookingResponse.setBaggageAllowance(booking.getBaggageAllowance());
bookingResponse.setDayOfDeparture(createWeirdDateClass(booking.getDayOfDeparture()));
bookingResponse.setDuration(booking.getDuration());
bookingResponse.setHourOfDeparture(booking.getHourOfDeparture());
return bookingResponse;
}
private XMLGregorianCalendar createWeirdDateClass(String lexicalRepresentation) {
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(lexicalRepresentation);
} catch (DatatypeConfigurationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
return null;
}
}
}
our spring service:
#Service
#Transactional
public class BookingServiceBeanImpl implements BookingServiceBean {
#Autowired
BookingDAO bookingDAO;
#Override public void createBooking(Booking booking) {
bookingDAO.createBooking(booking);
}
}
The spring bean can be used in the spring controllers so I don't think there's a problem there..

Resources