I am following spring data rest from https://spring.io/guides/gs/accessing-data-rest/ and I am only using
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
I would like to know how can I return all records (without pagination) but not using spring-boot-starter-web.I wants to keep my code as small as possible.
I tried following but it is not working
#RepositoryRestResource(collectionResourceRel = "people" , path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findAllByLastName(#Param("name") String name);
default List<Person> findAll(){
Pageable pageable = null;
return (List<Person>) this.findAll(pageable);
};
}
I mean if I have whole MVC, I can do it but I like to keep my code to minimum.
Spring Data REST is itself a Spring MVC application and is designed in
such a way that it should integrate with your existing Spring MVC
applications with little effort. An existing (or future) layer of
services can run alongside Spring Data REST with only minor additional
work.
If you are using current version of spring boot, there is no need to mark your repository with #RepositoryRestResource; also spring will auto-configure Spring Data Rest once it found the spring-data-rest dependency in your path, bellow you will find steps with minimum config :
In pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
Define your Entity + Repository :
Order.java
#Entity(name = "SampleOrder")
#Data
public class Order {
#Id #GeneratedValue//
private Long id;
private String name;
}
OrderRepository.java
public interface OrderRepository extends CrudRepository<Order, Long> {
}
Application.java
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Test your API :
curl http://localhost:8080
< HTTP/1.1 200 OK
< Content-Type: application/hal+json
{ "_links" : {
"orders" : {
"href" : "http://localhost:8080/orders"
}
}
}
As #abdelghani-roussi shows, you can use the CrudRepository instead of the PagingAndSortingRepository, e.g.:
public interface PersonRepository extends CrudRepository<Person, Long> {
List<Person> findAllByLastName(#Param("name") String name);
// don't need to define findAll(), it's defined by CrudRepository
}
and then the default findAll() method will return a List<Person> that isn't paged.
Note: as I mentioned in my comment, by including the dependency on spring-boot-starter-data-rest you are also pulling in the Web dependencies, so you can't avoid that.
Related
In my spring boot app, I want to write a web-test.
My application returns a list of strings. The test however produces a list with only one element (complete json as string).
My (minimal example) production code:
#SpringBootApplication
public class BackendApplication {
public static void main(String[] args) {
SpringApplication.run(BackendApplication.class, args);
}
}
#RestController
#RequestMapping("/allBoxes")
class StackOverFlowController {
#GetMapping
public List<String> getNamesOfAllBoxes() {
return List.of("Fruits", "Regional");
}
}
My test class:
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class StackOverFlowControllerTest {
#Autowired
WebTestClient webTestClient;
#Test
void whenListOfStringsEndpoint_thenExpectListOfStrings(){
// When
List<String> actual = webTestClient.get()
.uri("/allBoxes")
.exchange()
.expectStatus().is2xxSuccessful()
.expectBodyList(String.class)
.returnResult()
.getResponseBody();
// Then
Assertions.assertEquals(List.of("Fruits", "Regional"), actual);
}
}
My maven dependencies (spring boot 2.7.0 parent):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
The test fails:
org.opentest4j.AssertionFailedError:
Expected :[Fruits, Regional]
Actual :[["Fruits","Regional"]]
However, if I access the production application via postman, I receive:
["Fruits","Regional"]
Why does the reactive WebTestClient not parse this json, but instead create an array with only one string? How can I tell it to parse the string and give me a list of strings (with my two items as elements) instead?
If you replace
.expectBodyList(String.class)
by
.expectBody(new ParameterizedTypeReference<List<String>>() {})
it works. Like this:
#Test
void whenListOfStringsEndpoint_thenExpectListOfStrings(){
// When
List<String> actual = webTestClient.get()
.uri("/allBoxes")
.exchange()
.expectStatus().is2xxSuccessful()
.expectBody(new ParameterizedTypeReference<List<String>>() {})
.returnResult()
.getResponseBody();
// Then
Assertions.assertEquals(List.of("Fruits", "Regional"), actual);
}
Check the default behaviour of Jackson2Decoder of Spring WebClient
https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-codecs-jackson
For a multi-value publisher, WebClient by default collects the values with Flux#collectToList() and then serializes the resulting collection.
You will need to deserialize accordingly.
Use Case :-
We are using Spring-data-aerospike to get and save the aerospike record.
Problem :- We are performing SAVE into two different aerospike sets and both of these SAVES should happen in an transactional manner i.e. if 2nd write fails, then the first write should also get rolled back.
Here is code-snippet looks like :-
#Document(collection = "cust", expiration = 90, expirationUnit = TimeUnit.DAYS)
public class Customer {
#Id
#Field(value = "PK")
private String custId;
#Field(value = "mobileNumber")
private String mobileNumber;
}
#Document(collection = "custDetails", expiration = 90, expirationUnit = TimeUnit.DAYS)
public class CustomerDetails {
#Id
#Field(value = "PK")
private String custDetailsId;
#Field(value = "addnDetails")
private Map additionalDetails;
}
#Repository
public interface CustomerRepository extends AerospikeRepository<Customer, String> {}
#Repository
public interface CustomerDetailsRepository extends AerospikeRepository<CustomerDetails, String>{}
#Autowired
AerospikeTemplate aerospikeTemplate;
This is what we want to achieve, which is not working right now :--
#Transactional(isolation = Isloation.SERIALIZABLE, rollbackFor=Exception.class)
public ResponseDTO<String> updateCustomer(CustomerUpdateRequest custUpdateReqDTO) {
Optional<Customer> cust = customerRepository.findById(custUpdateReqDTO.getCustId());
// Update Business logic of Customer Record.
aerospikeTemplate.update(cust);
Optional<CustomerDetails> custDet = customerDetailsRepository.findById(custUpdateReqDTO.getCustDetId());
// Update Business logic of CustomerDetails Record.
aerospikeTemplate.update(custDet);
}
Here is dependencies looks like :-
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>aerospike-client</artifactId>
<version>4.1.3</version>
</dependency>
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>spring-data-aerospike</artifactId>
<version>${aerospike.data.version}</version>
<scope>system</scope>
<systemPath>${basedir}/lib/spring-data-aerospike-2.0.0.RELEASE.jar</systemPath>
</dependency>
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>aerospike-client</artifactId>
</dependency>
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>aerospike-helper-java</artifactId>
<version>1.2.2</version>
</dependency>
Questions :-
We are aware that spring transactional annotations works with RDBMS !! Whats the way to get the transactional property working here in this scenario ??
Any help or suggestions shall be highly appreciated !
Aerospike has transaction support for single record only. You will need to perform insert-rollback logic inside your application for multiple records.
Im trying to work through a few tutorials of quarkus and got a problem with creating a simple REST endpoint. Im following this tutorial: https://quarkus.io/guides/rest-data-panache .
Im using the approach from the guide to create an interface that extends PanacheEntityResource<Entity, Id>
public interface ActorResource extends PanacheEntityResource<Actor, Long>{
}
The respective Entity is:
#Entity
public class Actor extends PanacheEntity{
public String first_name;
public String last_name;
public Timestamp last_update;
public static List<Actor> findByFirstName(String name) {
return list("first_name", name);
}
}
As in the guide, doing it like this auto-generates the basic rest endpoints for getById, getAll, create, update and delete. As you can see in my Entity class I have a findByFirstName method which gets all Entities, which match the given method parameter "name" . Now I want to expose a REST endpoint for this method. Ive so far found a way to implement this, but that doesnt seem quite right. Ive had no luck with implementing the REST endpoint for the method directly into the interface
#ResourceProperties(path = "actors")
public interface ActorResource extends PanacheEntityResource<Actor, Long>{
#GET
#Produces("application/json")
#Path("/first_name={name}")
public static List<Actor> getByFirstName(#PathParam("name") String name) {
return Actor.findByFirstName(name);
}
}
No errors with this implementation, but the REST endpoint isnt exposed.
Now as I said, Ive found a way to do this and this is to create an interface as shown in the first code bracket with nothing in it and in addition to that a ResourceClass in which I implement my custom endpoint. To reduce the clutter (in the IDE) Ive combined this so the interface is created inside my ResourceClass like this (example is for another entity):
#Path("/countries")
#ApplicationScoped
#Produces("application/json")
public class CountryResource {
#GET
#Path("/name={name}")
public List<Country> getByName(#PathParam("name") String name) {
return Country.findByName(name);
}
#ResourceProperties(path = "/countries")
public interface CountryResourceTest extends PanacheEntityResource<Country, Long>{
}
}
This works, by creating the interface the basic rest endpoints are auto-generated and inside the resource class I can add other endpoints, but it just feels like this is not the right approach. Am I wrong, and this is just how Im supposed to do this, or is there a way to implement this with only the interface approach that was originally used in the guide?
I think adding custom endpoints straight to generated resource classes isnt supported yet because this is still an experimental feature for evaluation only. Feel free to give feedback as issues in quarkus' GitHub issue tracker.
I think the best way to add custom endpoints is by creating a second resource class with the same path. Then you can define your custom endpoints there. If you have no name collisions that will work. I tested it with the hibernate-orm-panache-quickstart with following code changes:
My Entity with my custom query:
#Entity
#Cacheable
public class Fruit extends PanacheEntity {
#Column(length = 40, unique = true)
public String name;
public Fruit() {
}
public Fruit(String name) {
this.name = name;
}
public static Fruit findByName(String name) {
return find("name=?1", name).firstResult();
}
}
Resource for generated rest-api (remoe the given resource in this tutorial):
public interface FruitResource extends PanacheEntityResource<Fruit, Long> {
}
My specific resource:
#Path("fruit")
#ApplicationScoped
#Produces("application/json")
#Consumes("application/json")
public class FruitSpecificResource {
#GET
#Path("/first_name={name}")
public Fruit getByName(#PathParam("name") String name) {
return Fruit.findByName(name);
}
}
I also added openapi and replaced postgres with h2 for testing purposes. Here are my dependencies:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm-panache</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jsonb</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-h2</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-openapi</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm-rest-data-panache</artifactId>
</dependency>
And i changed the application.properties to this:
quarkus.datasource.db-kind=h2
quarkus.datasource.jdbc.url=jdbc:h2:mem:test
quarkus.datasource.jdbc.max-size=8
quarkus.datasource.jdbc.min-size=2
quarkus.hibernate-orm.database.generation=drop-and-create
quarkus.hibernate-orm.log.sql=true
quarkus.hibernate-orm.sql-load-script=import.sql
Ok, now i can start quarkus:dev and there will be a swagger-ui under localhost:8080/swagger-ui
The new endpoint is there. I tested it manually. It works.
I am making a rest service application with JAX-RS. Its for some project for school. For this project I need to use follow techniques:
• Maven
• JAX-RS
• CDI
• JPA - EJB
• JNDI
• Bean Validation
So now I already maded my domain "Cafes" with a Fake DB ("CafeStub") and a real DB using JPA ("CafeDB"). My domain also makes a little usage of CDI. (#Inject in the CafeService class ...)
Non I wanted to create my rest service, using JAX-RS. This worked fine:
My problem is when I try to use CDI again it fails and it gives an 500 exception, NullPointerException, "Severe: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container"
Full Stacktrace:
I don't know how to fix this, already searched a long time .. Hopefully somebody can help me :s
This is my "CafeController" class. Producing the rest service
Path("/cafes")
public class CafeController {
#Inject
private CafeFacade cafeFacade;
public CafeController() {
//this.cafeFacade = new CafeService();
}
#GET
#Produces("application/json")
public Response getCafes(){
try{
// test ........
ObjectMapper mapper = new ObjectMapper();
Cafe cafe = cafeFacade.getCafe(new Long(1));
String jsonInString = mapper.writeValueAsString(cafe);
return Response.status(200).entity(jsonInString).build();
}catch (JsonProcessingException jsonEx) {
System.out.println("Json Exception");
System.out.println(jsonEx.getMessage());
return null;
}
}
This one is the "CafeService" class, the one who implemented "CafeFacade"
public class CafeService implements CafeFacade {
#Inject
private CafeRepository cafeRepository;
public CafeService() {
//cafeRepository = new CafeStub();
//cafeRepository = new CafeDB("CafesPU");
}
#Override
public long addCafe(Cafe cafe) {
return this.cafeRepository.addCafe(cafe);
}
#Override
public Cafe getCafe(long cafeID) {
return this.cafeRepository.getCafe(cafeID);
}
Her you see the "CafeStub" class, the one who implemented "CafeRepository"
public class CafeStub implements CafeRepository {
private static Map<Long, Cafe> cafes;
private static long counter = 0;
public CafeStub() {
cafes = new HashMap<Long, Cafe>();
// adding some dara
this.addSomeData();
}
#Override
public long addCafe(Cafe cafe) {
if(cafe == null){
throw new DBException("No cafe given");
}
counter++;
cafe.setCafeID(counter);
cafes.put(cafe.getCafeID(), cafe);
return cafe.getCafeID();
}
#Override
public Cafe getCafe(long cafeID) {
if(cafeID < 0){
throw new DBException("No correct cafeID given");
}
if(!cafes.containsKey(cafeID)){
throw new DBException("No cafe was found");
}
return cafes.get(cafeID);
}
At least here you can see my pom.xml (dependencies from CafeService project) - web.xml (from CafeService project) and project structure ...
<dependencies>
<dependency>
<groupId>Cafes</groupId>
<artifactId>Cafes</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19.4</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19.4</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19.4</version>
</dependency>
</dependencies>
Thanks in advance ...
Cheers
Tom
A class annotated with just #Path does not mark the class as a CDI bean as it is not in the list of bean defining annotations in the CDI spec. Adding RequestScoped to the REST service marks it as a CDI bean so injection works as you've discovered.
This answer here lists the annotations which mark a class as a CDI bean.
Is #javax.annotation.ManagedBean a CDI bean defining annotation?
Solved .. RequestScoped did the trick.. Daimn searched so long for one annotation.
#RequestScoped
#Path("/cafes")
public class CafeController {
Still I don't understand why I need to use it.
#RequestScoped : CDI instantiates and manages the bean
-> I thought my bean.xml would have instantiates and manages the bean ?
To pass variables between steps I have the step methods belong to the same class, and use fields of the class for the passed information.
Here is an example as follows:
Feature: Demo
Scenario: Create user
Given User creation form management
When Create user with name "TEST"
Then User is created successfully
Java class with steps definitions:
public class CreateUserSteps {
private String userName;
#Given("^User creation form management$")
public void User_creation_form_management() throws Throwable {
// ...
}
#When("^Create user with name \"([^\"]*)\"$")
public void Create_user_with_name(String userName) throws Throwable {
//...
this.userName = userName;
}
#Then("^User is created successfully$")
public void User_is_created_successfully() throws Throwable {
// Assert if exists an user with name equals to this.userName
}
My question is if it is a good practice to share information between steps? Or would be better to define the feature as:
Then User with name "TEST" is created successfully
In order to share commonalities between steps you need to use a World. In Java it is not as clear as in Ruby.
Quoting the creator of Cucumber.
The purpose of a "World" is twofold:
Isolate state between scenarios.
Share data between step definitions and hooks within a scenario.
How this is implemented is language specific. For example, in ruby,
the implicit self variable inside a step definition points to the
current scenario's World object. This is by default an instance of
Object, but it can be anything you want if you use the World hook.
In Java, you have many (possibly connected) World objects.
The equivalent of the World in Cucumber-Java is all of the objects
with hook or stepdef annotations. In other words, any class with
methods annotated with #Before, #After, #Given and so on will be
instantiated exactly once for each scenario.
This achieves the first goal. To achieve the second goal you have two
approaches:
a) Use a single class for all of your step definitions and hooks
b) Use several classes divided by responsibility [1] and use dependency
injection [2] to connect them to each other.
Option a) quickly breaks down because your step definition code
becomes a mess. That's why people tend to use b).
[1] https://cucumber.io/docs/gherkin/step-organization/
[2] PicoContainer, Spring, Guice, Weld, OpenEJB, Needle
The available Dependency Injection modules are:
cucumber-picocontainer
cucumber-guice
cucumber-openejb
cucumber-spring
cucumber-weld
cucumber-needle
Original post here https://groups.google.com/forum/#!topic/cukes/8ugcVreXP0Y.
Hope this helps.
It's fine to share data between steps defined within a class using an instance variable. If you need to share data between steps in different classes you should look at the DI integrations (PicoContainer is the simplest).
In the example you show, I'd ask whether showing "TEST" in the scenario is necessary at all. The fact that the user is called TEST is an incidental detail and makes the scenario less readable. Why not generate a random name (or hard code something) in Create_user_with_name()?
In Pure java, I just use a Singleton object that gets created once and cleared after tests.
public class TestData_Singleton {
private static TestData_Singleton myself = new TestData_Singleton();
private TestData_Singleton(){ }
public static TestData_Singleton getInstance(){
if(myself == null){
myself = new TestData_Singleton();
}
return myself;
}
public void ClearTestData(){
myself = new TestData_Singleton();
}
I would say that there are reasons to share information between steps, but I don't think that's the case in this scenario. If you propagate the user name via the test steps then it's not really clear from the feature what's going on. I think it's better to specifically say in the scenario what is expected. I would probably do something like this:
Feature: Demo
Scenario: Create user
Given User creation form management
When Create user with name "TEST"
Then A user named "TEST" has been created
Then, your actual test steps might look something like:
#When("^Create user with name \"([^\"]*)\"$")
public void Create_user_with_name(String userName) throws Throwable {
userService.createUser(userName);
}
#Then("^A user named \"([^\"]*)\" has been created$")
public void User_is_created_successfully(String userName) throws Throwable {
assertNotNull(userService.getUser(userName));
}
Here my way: I define a custom Scenario-Scope with spring
every new scenario there will be a fresh context
Feature #Dummy
Scenario: zweites Scenario
When Eins
Then Zwei
1: Use spring
<properties>
<cucumber.version>1.2.5</cucumber.version>
<junit.version>4.12</junit.version>
</properties>
<!-- cucumber section -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-spring</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<!-- end cucumber section -->
<!-- spring-stuff -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.4.RELEASE</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.4.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>2.4.0.RELEASE</version>
<scope>test</scope>
</dependency>
2: build custom scope class
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component
#Scope(scopeName="scenario")
public class ScenarioContext {
public Scenario getScenario() {
return scenario;
}
public void setScenario(Scenario scenario) {
this.scenario = scenario;
}
public String shareMe;
}
3: usage in stepdef
#ContextConfiguration(classes = { CucumberConfiguration.class })
public class StepdefsAuskunft {
private static Logger logger = Logger.getLogger(StepdefsAuskunft.class.getName());
#Autowired
private ApplicationContext applicationContext;
// Inject service here : The impl-class need #Primary #Service
// #Autowired
// IAuskunftservice auskunftservice;
public ScenarioContext getScenarioContext() {
return (ScenarioContext) applicationContext.getBean(ScenarioContext.class);
}
#Before
public void before(Scenario scenario) {
ConfigurableListableBeanFactory beanFactory = ((GenericApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerScope("scenario", new ScenarioScope());
ScenarioContext context = applicationContext.getBean(ScenarioContext.class);
context.setScenario(scenario);
logger.fine("Context für Scenario " + scenario.getName() + " erzeugt");
}
#After
public void after(Scenario scenario) {
ScenarioContext context = applicationContext.getBean(ScenarioContext.class);
logger.fine("Context für Scenario " + scenario.getName() + " gelöscht");
}
#When("^Eins$")
public void eins() throws Throwable {
System.out.println(getScenarioContext().getScenario().getName());
getScenarioContext().shareMe = "demo"
// you can save servicecall here
}
#Then("^Zwei$")
public void zwei() throws Throwable {
System.out.println(getScenarioContext().getScenario().getName());
System.out.println(getScenarioContext().shareMe);
// you can use last service call here
}
#Configuration
#ComponentScan(basePackages = "i.am.the.greatest.company.cucumber")
public class CucumberConfiguration {
}
the scope class
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
public class ScenarioScope implements Scope {
private Map<String, Object> objectMap = Collections.synchronizedMap(new HashMap<String, Object>());
/** (non-Javadoc)
* #see org.springframework.beans.factory.config.Scope#get(java.lang.String, org.springframework.beans.factory.ObjectFactory)
*/
public Object get(String name, ObjectFactory<?> objectFactory) {
if (!objectMap.containsKey(name)) {
objectMap.put(name, objectFactory.getObject());
}
return objectMap.get(name);
}
/** (non-Javadoc)
* #see org.springframework.beans.factory.config.Scope#remove(java.lang.String)
*/
public Object remove(String name) {
return objectMap.remove(name);
}
/** (non-Javadoc)
* #see org.springframework.beans.factory.config.Scope#registerDestructionCallback(java.lang.String, java.lang.Runnable)
*/
public void registerDestructionCallback(String name, Runnable callback) {
// do nothing
}
/** (non-Javadoc)
* #see org.springframework.beans.factory.config.Scope#resolveContextualObject(java.lang.String)
*/
public Object resolveContextualObject(String key) {
return null;
}
/** (non-Javadoc)
* #see org.springframework.beans.factory.config.Scope#getConversationId()
*/
public String getConversationId() {
return "VolatileScope";
}
/**
* vaporize the beans
*/
public void vaporize() {
objectMap.clear();
}
}
Other option is to use ThreadLocal storage. Create a context map and add them to the map. Cucumber JVM runs all the steps in the same thread and you have access to that across all the steps. To make it easier, you can instantiate the storage in before hook and clear in after hook.
If you are using Serenity framework with cucumber you can use current session.
Serenity.getCurrentSession()
more about this feature in http://thucydides-webtests.com/2012/02/22/managing-state-between-steps/. (Serenity was called Thucydides before)