Define a bean from external library - spring

I have a poblem.
I am working with api binance and I add this library to use all functionalities.
<dependency>
<groupId>io.github.binance</groupId>
<artifactId>binance-connector-java</artifactId>
<version>1.3.0</version>
</dependency>
This is the code of external library
public class Market {
private final String baseUrl;
private final RequestHandler requestHandler;
private final boolean showLimitUsage;
public Market(String baseUrl, String apiKey, boolean showLimitUsage) {
this.baseUrl = baseUrl;
this.requestHandler = new RequestHandler(apiKey);
this.showLimitUsage = showLimitUsage;
}
When I try to inject this classe I always receive the following error on SpringBoot
Consider defining a bean of type 'com.binance.connector.client.impl.spot.Market' in your configuration.
I have an controller and I use like this.
#RestController
public class ExampleController {
#Autowired
private Market market;
#RequestMapping(value = "/ping", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> ping() {
return ResponseEntity.ok(market.ping());
}
}
I try to add the class with ComponentScan.
The code of external library is only for read.

Related

#RepositoryRestController not recognized

I have the following controller:
#RepositoryRestController
public class TestController {
#RequestMapping(value = "/testables", method = RequestMethod.GET)
public String get(){
return "testin it";
}
}
And it is not picked up by Spring. I get 404 when I hit /apiroot/testables address. If I change it to be #RestController and add the api root to request mapping value, then it works. Also, if I change the mapping to point to "/orders/testables", it works as #RepositoryRestController. I also have the following controller in the same package which works fine:
#RepositoryRestController
public class SendEmailController {
#Autowired
private MessageSource messageSource;
#Autowired
private JavaMailSender javaMailSender;
#Autowired
private OrderRepository orderRepository;
#RequestMapping(value = "/orders/{id}/sendOrderEmailToSupplier")
public void sendOrderEmailToSupplier(#PathVariable("id") Long id, WebRequest request) throws MessagingException {...
#RepositoryRestController deal with basePath only for resources which it manage. In other cases the path should not contain the "base".
If you want to build custom operations underneath basePath, you can use #BasePathAwareController.

Spring Data MongoDB custom repository method implementation

I followed the instructions outlined here to implement custom methods for my MongoDB Repository. However, none of the custom methods appear to be usable (findAllSeries and uploadSomeSeries do not seem to be found by spring). I have checked the naming
SeriesRepository:
#RepositoryRestResource(collectionResourceRel = "series", path = "series", excerptProjection = SeriesProjection.class)
public interface SeriesRepository extends MongoRepository<Series, String>, SeriesRepositoryCustom {
List<Series> findByWinnerId(#Param("id") String id);
}
SeriesRepositoryCustom:
public interface SeriesRepositoryCustom {
ResponseEntity<Void> createSeries(Series series);
}
SeriesRepositoryImpl:
public class SeriesRepositoryImpl implements SeriesRepositoryCustom {
private final MongoOperations operations;
#Autowired
public SeriesRepositoryImpl(MongoOperations operations) {
this.operations = operations;
}
#Override
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> createSeries(#RequestBody Series series) {
// ... implementation
}
}
Got it working; via this answer, I had to implement a controller for my repository, and delegate the call to the method defined in the custom repository:
#RepositoryRestController
public class SeriesController {
private final SeriesRepository repository;
#Autowired
public SeriesController(SeriesRepository repo) {
repository = repo;
}
#RequestMapping(value = "/series", method = RequestMethod.POST)
public ResponseEntity<Void> create(#RequestBody Series series) {
return repository.createSeries(series);
}
}

Spring Data Rest : How to expose custom rest controller method in the HAL Browser

i have created a custom rest controller and I can access the API and get the result from the resource, the problem is, it doesn't appear in the HAL Browser.. how to expose this custom method in the HAL Browser? Thank You...
#RepositoryRestController
public class RevisionController {
protected static final Logger LOG = LoggerFactory
.getLogger(RevisionController.class);
private final DisciplineRepository repository;
Function<Revision<Integer, Discipline>, Discipline> functionDiscipline = new Function<Revision<Integer, Discipline>, Discipline>() {
#Override
public Discipline apply(Revision<Integer, Discipline> input) {
return (Discipline) input.getEntity();
}
};
#Inject
public RevisionController(DisciplineRepository repository) {
this.repository = repository;
}
#RequestMapping(method = RequestMethod.GET, value = "/disciplines/search/{id}/revisions")
public #ResponseBody ResponseEntity<?> getRevisions(
#PathVariable("id") Integer id) {
Revisions<Integer, Discipline> revisions = repository.findRevisions(id);
List<Discipline> disciplines = Lists.transform(revisions.getContent(),
functionDiscipline);
Resources<Discipline> resources = new Resources<Discipline>(disciplines);
resources.add(linkTo(
methodOn(RevisionController.class).getRevisions(id))
.withSelfRel());
return ResponseEntity.ok(resources);
}
}
Register a bean that implements a ResourceProcessor<RepositoryLinksResource> and you can add links to your custom controller to the root resource, and the HAL Browser will see it.
public class RootResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {
#Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
resource.add(ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(RevisionController.class).getRevisions(null)).withRel("revisions"));
return resource;
}
}

Spring MVC - Autowired field from header

I made web service with spring mvc(version 4).
This service used token in http header for authorization.
I want to value in http header bind to field in model class auto.
Is it possible? How can I do?
(See below code and comment)
Controller
#Controller
#RequestMapping(value = "/order")
public class OrderController {
private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
#Autowired
private OrderService orderService;
#RequestMapping(value = "/")
#ResponseBody
public List<Order> getAll() throws Exception {
// I want to remove two line below with auto binding (userToken field in model)
// in all controller using token value
String token = request.getHeader("X-Auth-Token"); // remove~
orderService.setUserToken(token); // remove~
orderService.getAllbyUser()
return items;
}
}
Model(Service)
#Service
public class OrderService {
//#Autowired - is it possible?
private String userToken;
public String setUserToken(String userToken)
{
this.userToken = userToken;
}
public List<Order> getAllbyUser() {
String userId = userMapper.getUserId(userToken);
List<Order> list = orderMapper.getAllbyUser(userId);
return list;
}
}
#Autowire is for Spring to inject beans one to another. If you want to inject a String to a bean you can with the org.springframework.beans.factory.annotation.Value annotation.
For example:
#Value("${user.token}")
private String userToken;
This will make Spring search of the user.token in the VM args and other places (which I don't remember and in some specific order).
But again, as said in my initial comment, from the code you show here it seems to be an error setting this field as it is context specific and the #Service (by default) indicates that the OrderService is a singleton.
In order to read a header value from request, you can use #RequestHeader("X-Auth-Token") in your controller, as shown below:
#RequestMapping(value = "/")
#ResponseBody
public List<Order> getAll(#RequestHeader("X-Auth-Token") String token) throws Exception {
orderService.setUserToken(token); // remove~
orderService.getAllbyUser()
return items;
}
Hope this helps you.

Creating an aspect on a spring #Controller with #Autowired final fields in constructor

I have an aspect setup
#Aspect
#Component
public class JsonAspect {
#Around("execution(public au.com.mycompany.common.json.response.JsonResponse *(..)) " +
"&& #annotation(org.springframework.web.bind.annotation.RequestMapping)")
public final Object beforeMethod(final ProceedingJoinPoint joinPoint) throws JsonException {
try {
System.out.println("before...................");
System.out.println(joinPoint.getSignature().getName());
return joinPoint.proceed();
} catch (Throwable t) {
throw new JsonException(t);
}
}
}
I this should apply to a #Controller class with the following method
#RequestMapping(value = "/validate",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public final JsonResponse<JsonValidationResponse> validateViaJson(...
The problem is that I am injecting dependencies via #Autowired
private final ClientService clientService;
private final VehicleService vehicleService;
#Autowired
public QuoteControllerImpl(
final ClientService clientService,
final VehicleService vehicleService,
) {
this.clientService = clientService;
this.vehicleService = vehicleService;
}
When I try to proxy this class it complains that there is no default constructor. so I decided to crate an interface for the class but now I get the following error on an unrelated method in the same class.
java.lang.IllegalArgumentException: object is not an instance of
declaring class
The above error applies to a method that is is in the same class but not part of the aspectj pointcut. If remove the aspectj pointcut it works (event with the new interface). So it seems that aspectj proxy is causing a problem somehow.
Anyone know why?
UPDATE
#nicholas.hauschild I tried your solution but now I am getting a NullPointer Exception when I initialise my map.
#ModelAttribute
public final void initialiseModel(final ModelMap map, #PathVariable("status") final String status) {
map.addAttribute(CLIENTS, clientService.getClients());
clientService is null.
I am not a huge fan of this solution, but if you create the default constructor along with the #Autowired one, Spring will use the #Autowiredone anyways.
private final ClientService clientService;
private final VehicleService vehicleService;
#Autowired
public QuoteControllerImpl(
final ClientService clientService,
final VehicleService vehicleService,
) {
this.clientService = clientService;
this.vehicleService = vehicleService;
}
public QuoteControllerImpl() {
//Spring won't use me...
this.clientService = null;
this.vehicleService = null;
}

Resources