Create bean using spring xml - java

How to create xml bean for the below java class. I am using old spring version, from where i need to create a xml bean for the following "TestSample" class.
#Service
#EnableConfigurationProperties(SampleProperties.class)
public class TestSample{
#Autowired
public ClientService clientService;
#Autowired
public RestTemplate restTemp;
public Map<String, String> testing(String a, String b, String c) throws Exception {
Map<String, String> map = clientService.find(a, b, c);
System.out.println("**=="+map.get(0));
return map;
}
}
ClientService class.
#Service
#Slf4j
#DependsOn("restTemp")
public class ClientService {
public ClientService(
#Autowired final SampleProperties sampleProperties,
#Autowired(required = false) final ObjectMapper pObjectMapper) throws UnknownHostException {
}
//......
}

Related

Spring Boot create instance of class passing in parameters to constructor

In Spring Boot I have a class that I want to instantiate by passing parameters in the the constructor in runtime. I am able to do this but all of the AutoWire properties are null and PostConstruct doesn't get called.
Constructor<KafkaController> constructorsA[] = (Constructor<KafkaController>[]) KafkaController.class.getConstructors();
KafkaController kafkaObject = constructorsA[0].newInstance(new Object[] { "1", "2" });
This is the class in question
#Component
public class KafkaController {
private KafkaConsumer<String, String> consumer;
#Autowired
private Util sentinelUtil;
final String subscriberID;
final String interactionID;
#Autowired
public KafkaController(#Value("") String subscriberID, #Value("") String interactionID) {
this.subscriberID = subscriberID;
this.interactionID = interactionID;
}
#PostConstruct
private void initKafka() {
}
}
Do I have to instantiate the class using a different method?

Full validation test in Spring Boot, injection failing

Hello everyone I wanted to tested the full validation of a Request in my Spring Boot application I mean no testing one validator at a time but all of them on the target object)
First I have my object :
public class UserCreationRequest {
#JsonProperty("profileId")
#NotNull
#ValidProfile
private Integer profileId;
}
Then my Validator (#ValidProfile):
#Component
public class ProfileValidator implements ConstraintValidator<ValidProfile, Integer> {
#Autowired
private IProfileService profileService;
#Autowired
private IUserRestService userRestService;
#Override
public void initialize(ValidProfile constraintAnnotation) {
}
#Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
RestUser restUser = userRestService.getRestUser();
ProfileEntity profileEntity = profileService.getProfile(value, restUser.getAccountId());
return profileEntity != null;
}
}
Now I write my unit test :
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = {ValidationTestConfiguration.class})
public class UserCreationRequestValidationTest {
private static LocalValidatorFactoryBean localValidatorFactory;
#Autowired
private IUserService userService;
#Autowired
private IProfileService profileService;
#Autowired
private IUserRestService restService;
#BeforeClass
public static void createValidator() {
localValidatorFactory = new LocalValidatorFactoryBean();
localValidatorFactory.setProviderClass(HibernateValidator.class);
localValidatorFactory.afterPropertiesSet();
}
#AfterClass
public static void close() {
localValidatorFactory.close();
}
#Test
public void validateUserCreationRequestStringfields() {
UserCreationRequest userCreationRequest = new UserCreationRequest();
/* Here fill test object*/
when(userService.getUser(any(Integer.class), any(Integer.class))).thenReturn(new UserEntity());
when(profileService.getProfile(any(Integer.class), any(Integer.class))).thenReturn(new ProfileEntity());
when(restService.getRestUser()).thenReturn(new RestUser());
Set<ConstraintViolation<UserCreationRequest>> violations
= localValidatorFactory.validate(userCreationRequest);
assertEquals(violations.size(), 8);
}
}
and my TestConfiguration is like that :
#Configuration
public class ValidationTestConfiguration {
#Bean
#Primary
public IProfileService profileService() {
return Mockito.mock(IProfileService.class);
}
#Bean
#Primary
public IUserRestService userRestService() { return Mockito.mock(IUserRestService.class); }
}
On execution I can see that in the test itself the injection works :
restService is mapped to "Mock for IUserRestService"
But in my validator it is not injected, userRestService is null.
Same thing for ProfileService
I tried several things seen here, nothing works (code is running, only test conf is failing)
This is because you do not produce the Validator bean so it can be injected.
As you manually instantiate the LocalValidatorFactoryBean, it cannot access to the spring DI defined for this test.
You should produce instead a bean for the Validator, or even reference an existing spring configuration to do so.

Wire multiple config classes using dependency injection

I have working configuration class in spring. I tried to replace hard-coded string by configuration map using dependency injection.
#Configuration
#Component
public class BwlConfiguration {
#Resource(name="loadParameters")
private Map<ConfigEnum, String> conf;
private String address;
public BwlConfiguration() {
address = conf.get(SPI_BL);
}
...
}
Class that provides conf map:
#Configuration
#Component
public class ConfigLoader {
#Resource(name="returnEnv")
private Map<String, String> env;
#Bean
public Map<ConfigEnum, String> loadParameters() throws ParameterNotSetException{
....
return parameterMap;
}
Class that provides env map:
#Configuration
public class EnvConf {
#Bean
public Map<String, String> returnEnv(){
return System.getenv();
}
}
When I run the program, nullPointerException is thrown at address = conf.get(SPI_BL); line. I tried to replace #Component by #Import(...class), same result and it's losing the point of injection.
Am I using these annotations wrong? Thanks
I replaced constructor in BwlConfiguration with:
#Bean
public String address(){
return conf.get(SPI_BL);
}

How to create a bean of repository class

I'm doing unit test using spring mvc test framework.
The following is my source code:
com.exmple.main
MyController.java
#Controller
public class MyController {
#Autowired
private MyService myService;
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public Map<Object, Object> myControllerFunction(#RequestBody final Object jsonRequest) {
/* do something */
return response;
}
}
MyRepository.java
#Repository
public interface MyRepository extends JpaRepository<My, String> {
#Query(value="select * from my d where (d.start_date<to_date(:date,'YYYY/DD/MM')) and (d.end_date>to_date(:date,'YYYY/DD/MM'))", nativeQuery=true)
List<My> findByDate(#Param("date") String date);
}
MyService.java
public interface MyService {
List<My> findByDate(String date);
}
MyServiceImpl.java
#Service
public class MyServiceImpl implements MyService {
#Autowired
MyRepository destRepo;
#Override
public List<My> findByDate(String date) {
List<My> listDest = destRepo.findByDate(date);
return listDest;
}
}
com.example.test
MyControllerTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes={TestConfig.class})
#WebAppConfiguration
public class MyControllerTest {
private MockMvc mockMvc;
#Autowired
MyService myService;
#Autowired
protected WebApplicationContext webApplicationContext;
#Before
public void setup() throws Exception {
// this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#Test
public void listAllMy() throws Exception {
}
}
TestConfig.java
#Configuration
public class TestConfig {
#Bean
public MyService myService() {
// set properties, etc.
return new MyServiceImpl();
}
}
When I run test, the following error is displayed
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException
I know the exception occurred because MyService didn't find any bean of MyRepository.
But I don't know how to create a bean of repository.
Please teach me how to create a bean of repository class using Java (not xml).
You need to enable the JPA repositories in your config class, specify the package that contains the repositories as below
#Configuration
#EnableJpaRepositories(basePackages = {
"com.example.repository"
})
public class TestConfig {
#Bean
public MyService myService() {
// set properties, etc.
return new DestinationServiceImpl();
}
}
Edit: looks like you haven't defined entityManager, and dataSource. Refer to a tutorial here and also answer to similar question here

#Configuration not working for Bean creation

I have the following code, where in i am trying to create a bean out of the return type of the method.
It give error while starting the application as below:
Error creating bean with name 'myMap' defined in class path resource
[com/test/MyServiceImpl.class]: No matching factory method found:
factory bean 'MyServiceImpl'; factory method 'myMap()'. Check that a
method with the specified name exists and that it is non-static.
Code:
#Configuration
public class MyServiceImpl implements MyService
{
#Autowired
private MyDao myDao;
#Override
#Bean
#Scope("singleton")
#Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Map<String, String> myMap()
{
return myDao.getMapFromDB();
}
}
public interface MyService
{
Map<String, String> myMap()
}
My application is based spring mvc and I have added the relevant configuration in the xml.
<mvc:annotation-driven/>
<context:component-scan>
I'm not 100% sure what you try to do, but here's an approach which would work:
#Service
public class MyServiceImpl implements MyService {
#Autowired
private MyDao myDao;
#Override
#Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Map<String, String> myMap() {
return myDao.getMapFromDB();
}
}
interface MyService {
Map<String, String> myMap()
}
This would define your service implementation as a Spring-managed #Service. Your MyDao would automatically be injected and you can use it in your method.
If you want that your MyDao has a certain scope (singleton is already the default), than you would annotate the MyDao class.
If you want to write a configuration, you would need to do it like this:
#Configuration
class MyConfig {
public MyService myService() {
return new MyServiceImpl();
}
}

Categories

Resources