I am succesfully running EJB tests with Arquillian against an (older) Glassfish 3.1 embedded.
When trying to #Inject weld beans, I get a NPE when I want to address a method in a transitively injected Weld bean.
So, I am testing EJB A. EJB A has a ref to EJB B. EJB B has a ref to a Weld bean.
This is the Jar init.
#Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(JavaArchive.class, "itscool.jar")
.addClasses(DashboardService.class, PropertyService.class, StorageService.class, EPSRepository.class,
EmailService.class, NotificationRepository.class, EmailRepository.class, Configuration.class,
MailingList.class, BogusBean.class, Bogus.class)
.addAsManifestResource("META-INF/persistence.xml", "persistence.xml")
.addAsManifestResource(EmptyAsset.INSTANCE, "META-INF/beans.xml")
.addAsResource(new File("src/test/resources/csman.properties"), "csman.properties");
}
So, the injected bean is the Configuration.class. First, I thought there was some initialization error in the Configuration impl class, so I created the #Bogus and BogusBean to only test the injection. I get the same errors.
#Bogus
public class BogusBean {
public void setIt(){
}
}
And the Qualifier
#Documented
#Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
#Retention(RetentionPolicy.RUNTIME)
#Qualifier
public #interface Bogus {
}
And the injection in the EmailService (a #stateless session bean).
#Inject
#Bogus
private BogusBean bogus;
#EJB
private EmailRepository emailRepos;
#PostConstruct
public void init() {
bogus.setIt();
}
The NPE happens on the bogus.setIt() line. as bogus == null.
This is the maven config
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<version>1.1.11.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.core</groupId>
<artifactId>arquillian-core-api</artifactId>
<version>1.1.11.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.weld.arquillian.container</groupId>
<artifactId>arquillian-weld-ee-embedded-1.1</artifactId>
<version>1.1.2.Final</version>
</dependency>
I added a Profile for the glassfish embedded
<profile>
<id>arquillian-glassfish-embedded</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-embedded-3.1</artifactId>
<version>1.0.0.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>3.1.2.2</version>
<!-- was 4.0 -->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.23.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.23.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
</profile>
I also tried to change from weld-ee to weld-se but then the container doesn't even start. (as stated here) : how-to-test-ejb-method-call-with-arquillian-weld-ee-embedded
Related
I have next structure:
Quarkus extension 'core' with interface SomeInterface and bean SomeContainer:
#ApplicationScoped
public class SomeContainer {
#Inject
SomeInterface someInterface;
}
Quarkus extension 'implementation' with SomeImpl bean:
#ApplicationScoped
public class SomeImpl implements SomeInterface {
}
Quarkus application - 'starter' which depend quarkus extension 'implementation' and jax rs controller:
#Path("/hello")
public class GreetingResource {
#Inject
SomeContainer someContainer;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String hello() {
}
}
When I try start app I get an error:
Caused by: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type by.test.core.SomeInterface and qualifiers [#Default]
How to fix it?
link to project https://github.com/flagmen/quarkus-test
Your starter module only depends on the core module which by itself does not contain a CDI injectable candidate for the SomeInterface.
You should add the implementation module holding the discoverable bean as a dependency as well:
<!-- quarkus-test/starter/pom.xml -->
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>by.test</groupId>
<artifactId>core</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>by.test</groupId>
<artifactId>implementation</artifactId> <!-- you can even omit the core module as it will be transitively imported -->
<version>1.0.0</version>
</dependency>
</dependencies>
I have a small JAX-RS (Jersey 3.0.1) API running in a standalone Jetty 11 but want to use Weld 4.0.0 instead of HK2. The Jetty bootstraps the Weld context properly (Jetty module ci-decorate was installed as described in the Weld documentation)
WELD-ENV-001212: Jetty CdiDecoratingListener support detected, CDI injection will be available in Listeners, Servlets and Filters.
When it comes to call the API endpoint an exception occurs:
WARNING: The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 1
org.jboss.weld.exceptions.IllegalStateException: WELD-001304: More than one context active for scope type jakarta.enterprise.context.RequestScoped
at org.jboss.weld.manager.BeanManagerImpl.internalGetContext(BeanManagerImpl.java:672)
at org.jboss.weld.manager.BeanManagerImpl.isContextActive(BeanManagerImpl.java:658)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:163)
at org.jboss.weld.contexts.unbound.DependentContextImpl.get(DependentContextImpl.java:64)
at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.get(ContextualInstanceStrategy.java:100)
at org.jboss.weld.bean.ContextualInstance.get(ContextualInstance.java:50)
at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:694)
at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:717)
at org.jboss.weld.util.ForwardingBeanManager.getReference(ForwardingBeanManager.java:64)
at org.jboss.weld.bean.builtin.BeanManagerProxy.getReference(BeanManagerProxy.java:87)
at org.glassfish.jersey.ext.cdi1x.internal.CdiUtil.getBeanReference(CdiUtil.java:127)
at org.glassfish.jersey.ext.cdi1x.internal.AbstractCdiBeanSupplier$1.getInstance(AbstractCdiBeanSupplier.java:69)
at org.glassfish.jersey.ext.cdi1x.internal.AbstractCdiBeanSupplier._provide(AbstractCdiBeanSupplier.java:103)
at org.glassfish.jersey.ext.cdi1x.internal.RequestScopedCdiBeanSupplier.get(RequestScopedCdiBeanSupplier.java:46)
at org.glassfish.jersey.inject.hk2.InstanceSupplierFactoryBridge.provide(InstanceSupplierFactoryBridge.java:53)
at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:129)
My dependencies in the pom.xml look as follows:
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet-core</artifactId>
<version>4.0.0.Final</version>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jakarta.ws.rs</groupId>
<artifactId>jakarta.ws.rs-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.cdi</groupId>
<artifactId>jersey-weld2-se</artifactId>
<version>3.0.1</version>
</dependency>
For the Weld context there exists an empty beans.xml in folder webapp/WEB-INF/beans.xml declared with bean-discovery-mode="all".
The JAX-RS endpoint class is shown next:
import de.test.weld.service.AddressRepository;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
#Path("address")
public class AddressApi {
#Inject
private AddressRepository addressRepository;
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getAddress() {
return "{\"street\": \"" + addressRepository.getStreet(0) + "\", \"postcode\": \"" +
addressRepository.getPostcode(0) + "\", \"city\": \"" + addressRepository.getCity(0) + "\"}";
}
}
The bean AddressRepositoryImpl which I want to inject is annotated with #jakarta.inject.Singleton.
I would appreciate any hint so it works with CDI Weld.
The problem was the wrong dependency
<dependency>
<groupId>org.glassfish.jersey.ext.cdi</groupId>
<artifactId>jersey-weld2-se</artifactId>
<version>3.0.1</version>
</dependency>
which exists only for non-JEE environments, i.e. Java Standard Edition (SE) or non-webapps.
Then the following dependency was still missing:
<dependency>
<groupId>org.glassfish.jersey.ext.cdi</groupId>
<artifactId>jersey-cdi1x</artifactId>
<version>3.0.1</version>
</dependency>
Solution refers to: Jersey Github Issues
I'm creating a web application using spring-boot with annotation based configuration.
At first, I created a spring application with annotation based config using Hibernate and JPA. It was working fine but then I needed to add spring-boot to my application and now cannot start it. Here is the code:
#SpringBootApplication
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Runner {
public static void main(String[] args) {
SpringApplication.run(Runner.class, args);
}
}
#Configuration
#EnableTransactionManagement
#ComponentScans(value = { #ComponentScan("com.alex.pharm.dao"),
#ComponentScan("com.alex.pharm.service") })
public class AppConfig {
#Bean
public LocalEntityManagerFactoryBean geEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("LOCAL_PERSISTENCE");
return factoryBean;
}
#Bean
#ConditionalOnMissingBean(type = "JpaTransactionManager")
public JpaTransactionManager geJpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(geEntityManagerFactoryBean().getObject());
return transactionManager;
}
}
#RestController
public class HelloController {
#RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
<groupId>com.sachatol.pharmacy</groupId>
<artifactId>pharmacyWebStore</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!-- Hibernate 5.2.9 Final -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
But when I try to run it I get the following exception:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization
- cancelling refresh attempt:org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'requestMappingHandlerMapping'
defined in class path resource
[org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]:
Initialization of bean failed; nested exception is java.lang.NoSuchMethodError:
org.springframework.web.servlet.handler.AbstractHandlerMapping.obtainApplicationContext()
Lorg/springframework/context/ApplicationContext;
How can I fix it?
Issue found - I used the old version for spring-context in pom (4.3.7.RELEASE) which override the one that spring-boot has and was the reason of NoSuchMethodError. So spring-context dependency was old and obsolete after removing or changing it to newer version (5.0.3) application started fine
Your #RequestMapping seems missing some parts, try with something like that:
#RequestMapping(value = "/", method = RequestMethod.GET)
This also happens if you have two methods with same request mapping values. Make sure you have unique RequestMapping values.
In your request mapping, you have incorrectly used :
#RequestMapping("/")
Instead, use this mapping to specify the end-point and the request-method like this :
#RequestMapping(value = "/", method = RequestMethod.GET)
Hope it will solve your problem.
I'm using Wildfly 10, Jersey, and injecting dependencies with #Inject. I have DAO and Service interfaces with their implementations declared in a CustomBinder. The injections work well, but the EntityManager is injected null with the #PersistenceContext annotation. I'm using MySQL and the datasource test-connection is working.
API Rest class
#Path("/account")
public class CuentaServiceRS {
#Inject
private ICuentaService cuentaService;
#GET
#Produces(MediaType.APPLICATION_JSON)
public Cuenta getCuenta() {
return cuentaService.getCuentas().get(0);
}
}
The implementation of ICuentaService
#Stateless
public class CuentaServiceImpl implements ICuentaService {
#Inject
private ICuentaDAO cuentaDAO;
#Override
public List<Cuenta> getCuentas() {
List<Cuenta> cuentas = cuentaDAO.getAllCuentas();
cuentas;
}
}
The implementation of CuentaDAO
#Stateless
public class CuentaDAOImpl implements ICuentaDAO {
#PersistenceContext(unitName = "altitudePU")
protected EntityManager em;
#Override
public List<Cuenta> getAllCuentas() {
CriteriaQuery<Cuenta> cq = em.getCriteriaBuilder().createQuery(Cuenta.class);
/...
return resultlist;
}
}
My persistence-unit in persistence.xml
<persistence-unit name="altitudePU">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/AltitudePU</jta-data-source>
<class>ar.com.olx.domain.Cuenta</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
The servlet configured on web.xml
<servlet>
<servlet-name>altitudeservlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>ar.com.villat.bind.ApplicationJaxRS</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
My custom AplicationJaxRS which extendes from ResourceConfig
public class ApplicationJaxRS extends ResourceConfig {
public ApplicationJaxRS(){
register(new CustomBinder());
packages(true, "ar.com.olx");
}
}
The CustomBinder
public class CustomBinder extends AbstractBinder {
#Override
protected void configure() {
bind(CuentaServiceImpl.class).to(ICuentaService.class);
bind(CuentaDAOImpl.class).to(ICuentaDAO.class);
}
}
And finally, my pom.xml dependencies related to this post
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<version>1.0.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
<scope>provided</scope>
</dependency>
If you need more information, please tell me.
As you are using a full stack JavaEE server you can simplify this a lot.
If you have not added a MySQL datasource to WildFly then you can do it like this:
WildFly Datasource Setup
Create a file called deploy-mysql-ds.cli with the following content:
# Execute offline
embed-server --server-config=standalone.xml
deploy $HOME/.m2/repository/mysql/mysql-connector-java-5.1.39.jar
# Add the application datasource
data-source add \
--name=AltitudeDS \
--driver-name=mysql-connector-java-5.1.39.jar \
--connection-url=jdbc:mysql://localhost:3306/altitudeDB \
--jndi-name=java:jboss/datasources/AltitudePU \
--user-name=$USER_NAME \
--password=$PASSWORD
Replace $HOME, $USER_NAME and $PASSWORD with real values
Configure the data source in Wildfly by executing it like:
$JBOSS_HOME/bin/jboss-cli.sh --file="deploy-mysql-ds.cli"
You only need to do this once.
Note that the --jndi-name matches the <jta-data-source>...</jta-data-source> in
your persistence.xml file.
You do not need the mysql-connector-java-5.1.39.jar in your maven dependencies because it has been added to the server directly. There are other solutions that involve adding the jar as a "module"
but I find this way to be much simpler.
Amend Application
Amend your application as follows:
Remove all the redundant dependencies:
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
Remove the AplicationJaxRS and CustomBinder classes and add a JAXRSConfiguration class:
/**
* Configures a JAX-RS endpoint
*/
#ApplicationPath("resources")
public class JAXRSConfiguration extends Application {
}
Remove the altitudeservlet from the web.xml. If that is the only thing in it then completely remove the whole file.
Test it
You should be able to deploy this web application and access it from:
http://localhost:8080/altitude-webapp/resources/account
where altitude-webapp is the name of your WAR file.
I have a spring boot application and I am writing an integration test class.
When I run my test class, I get the following exception
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.whot.dao.HotspotDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:589) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
I have searched for a while and looked for clues as to what might be causing this but I have not been able to come up with the reason this happens. Help would be appreciated. I have included some details of my code.
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>${spring.boot.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>${spring.boot.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${psql.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
</dependencies>
I have this in my Application.Java class
package com.whot;
#SpringBootApplication
#ComponentScan(basePackages = {"com.whot.controller"})
#EntityScan(basePackages = {"com.whot.entity"})
#EnableJpaRepositories(basePackages = {"com.whot.repository", "com.whot.dao"})
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
and in my integration class
package com.whot.dao;
#RunWith(SpringRunner.class)
#DataJpaTest
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class HotspotDaoIntegrationTest {
#Autowired
private HotspotDao hotspotDao;
#Autowired
private TestEntityManager entityManager;
private String hotspotName = "Mavericks";
#Test
public void givenHotspotNameReturnHotspotSuccessfully(){
Address address = new Address("Allen Mgba Crescent", 30L);
entityManager.persist(address);
Hotspot hotspot = new Hotspot(hotspotName);
entityManager.persist(hotspot);
entityManager.flush();
HotspotLocation hsLocation = new HotspotLocation(address);
hsLocation.setHotspotId(hotspot.getId());
entityManager.persist(hsLocation);
hotspot.getHotspotLocations().add(hsLocation);
HotspotDTO hotspotDto =((ArrayList<HotspotDTO>) hotspotDao.getHotspotByName(hotspotName)).get(0);
assertEquals(hotspotDto.getId(), hotspot.getId());
assertEquals(hotspotDto.getName(), hotspot.getName());
}
}
and the class in question here
package com.whot.dao;
#Component
public class HotspotDao {
#Autowired
HotspotRespository hsRepository;
public Collection<HotspotDTO> getHotspotByName(String hotspotName) {
Collection <HotspotDTO> hotspots = getHotspotsByName(Arrays.asList(hotspotName));
return hotspots;
}
public Collection<HotspotDTO> getHotspotsByName(Collection <String> names) {
Collection<Hotspot> hotspots = hsRepository.findHotspotsByName(names);
Collection<HotspotDTO> result = new ArrayList<>();
for(Hotspot hotspot: hotspots){
result.add(new HotspotDTO().toHotspotDto(hotspot));
}
return result;
}
}
Spring Boot default scan will start the same package and subpackers with startup application class.
If the other annotation is not in the same package, it will not be able to scan, the solution is to use the #ComponentScan annotation on startup application class, declare the package scan path. like...
#ComponentScan(basePackages={"com.exp.package1","com.exp.package2"})