I have the following Spring Java configuration set up:
#Configuration
public class FooConfig {
#Autowired
private IReferenceDataDAO referenceDataDAO;
#Bean
public IReferenceDataService getReferenceDataService() {
return new ReferenceDataServiceImpl(referenceDataDAO);
}
}
I am trying to reference the ReferenceDataService bean in another configuration class using the #Autowire property:
#Configuration
public class BarConfig {
#Autowired
private IRuleService ruleService;
#Autowired
private IReferenceDataService referenceDataService;
}
Here is the config that defines the IReferenceDataDAO:
#Configuration
public class FooBarConfig {
#Bean
public IReferenceDataDAO getReferenceDataDAO() {
return new ReferenceDataDAOImpl(getStaticData(), getMapper());
}
}
Here is the ReferenceDataServiceImpl:
public class ReferenceDataServiceImpl implements IReferenceDataService {
private IReferenceDataDAO dao;
public ReferenceDataServiceImpl(IReferenceDataDAO dao) {
this.dao = dao;
}
The above configs are imported in a master config class:
#Configuration
#Import({
FoosAppConfig.class,
BarAppConfig.class,
FooBarAppConfig.class,
})
I am noticing that this configuration leads to the referenceDAO in the ReferenceDataServiceImpl being set to null. What am I doing wrong? Shouldn't that #Autowire annotation ensure that my bean is fully configured before setting it?
BarConfig needs to import FooConfig
#Import({ FooConfig.class })
Try this:
#Configuration
#Import({ FooConfig.class })
public class BarConfig {
#Autowired
private IRuleService ruleService;
#Autowired
private IReferenceDataService referenceDataService;
}
This allows BarConfig to get access to the IReferenceDataService bean.
Related
I have a pojo class which i need to inject in component. how to inject pojo object in spring?
For example
RestClass is under Module(like one microservice). Pojo Value should be injected here only. service class and pojo is different module.
#Controller
public class RestClass {
#Autowired
private ServiceClass serviceClass;
// How to apply MyConfig pojo object into ServiceClass
//like MyConfig.Builder().limit(100).build();
#PostMapping("/business")
private void callDoBusiness(){
serviceClass.doBusiness();
}
}
//// ServiceClass and Pojo class is under one module. Pojo object should not construct here. should be passed from another module
#Service
public class ServiceClass {
#Autowired
private MyConfig myConfig;
public void doBusiness(){
System.out.println(myConfig.getLimit())
}
}
#Builder
#Getter
public class MyConfig {
private int limit;
.
.
}
#Bean annotation is used in your case. For example:
Create some configuration file with #Configuration annotation. It doesn't matter where you create your Config configuration class or how you name it. You can even have multiple #Configuration classes across your project.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
class Config {
// configure your MyConfig class here as a bean
#Bean
public MyConfig myConfig() {
return MyConfig.Builder().limit(100).build();
}
}
Now you can autowire it wherever you use it as in you example.
You can use #Configuration and #Bean. Something like this
AppConfig.java
#Configuration
public class AppConfig {
#Bean
public PojoClass getBean(){ return new PojoClass();}
}
You can use #Bean
#Configuration
public class Config {
#Bean
public MyConfig MyConfig() {
return new MyConfig();
}
}
I have a Spring boot 2.3.3.RELEASE project.
Main Application class,
#SpringBootApplication()
public class TestApplication {
...
}
#ConfigurationProperties(prefix = "test")
public class TestProperties {
...
}
#Configuration
#EnableConfigurationProperties({TestProperties.class})
public class TestConfiguration {
}
#Service
public class AmazonEmailService {
private final AmazonSimpleEmailService client;
#Autowired
private TestProperties props;
public AmazonEmailService() {
props.getEmail(); // Here props is null ...
}
}
Here, TestProperties autowiring is null in AmazonEmailService. Not sure what is missing.
Other Autowiring works in other classes.
Can you use #Autowired on the constructor instead?
private TestProperies props;
#Autowired
public AmazonEmailService(TestProperties props){
this.props=props;
props.getEmail(); //Ok now.
}
This is because using #Autowired on property, Spring inject the value AFTER object create. But in your case, you try to use the props inside the contructor. At that moment, it's still null
Add #Component annotation on TestProperties class
i would like to load #Configuration classes in an order. i have two configuration classes. i am having a requirement of loading my SampleProperties class before sampleconfiguration class.
I have tried the following annotations but it is not working as expected.
#AutoConfigureAfter(SampleProperties.class )
#AutoConfigureBefore(SampleConfiguration.class)
I have put my congiurations class in diff package in order to read configurations classes in an order.using #Import function, i am including my configuration classes into my application
My Main Class:
#Import({SampleProperties.class,SampleConfiguration.class,})
public class SampleApplication{
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
My SampleProperties Class
#Configuration
#AutoConfigureBefore(SampleConfiguration.class)
#ConfigurationProperties("demo")
#Data
public class SampleProperties {
private String team;
private int teamSize;
private String teamLeader;
}
My sampleconfiguration Class:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef="sampleEntityManager",
transactionManagerRef="sampleTransactionManager",
basePackages= {"com.example.demo.repo"})
#AutoConfigureAfter(SampleProperties.class)
public class SampleConfiguration {
#Autowired
Environment env;
#Bean(name="sampleDataSource")
#Primary
public DataSource dmsDataSource() {
// functions
return null;
}
#Primary
#Bean(name = "sampleEntityManager")
public LocalContainerEntityManagerFactoryBean dmsEntityManagerFactory(EntityManagerFactoryBuilder builder) {
// functions
return null;
}
#Primary
#Bean(name = "sampleTransactionManager")
public PlatformTransactionManager dmsTransactionManager(#Qualifier("sampleEntityManager") EntityManagerFactory entityManagerFactory) {
// functions
return null;
}
}
can anyone tell me what missing and where am making mistakes?
I think you have to use #Order annotation.
#Component
#Order(1)
public class SampleProperties {
// code
}
#Component
#Order(2)
public class SampleConfiguration {
// code
}
I have that class as you can see below:
#Configuration
#PropertySource("classpath:sample.properties")
public class SampleConfig {
#Value("${attr1.prop}")
private String attr1;
#Value("${attr2.prop}")
private String attr2;
#Bean
public SampleService sampleService() {
return new SampleService(attr1);
}
#Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
I created SampleService bean with parameter attr1. Is possible get access to that properties which I load with #PropertySource later? For example after #Autowired.
Here is code of of using that bean:
#Service
public class SuperHotServiceImpl {
#Autowired
SampleService sammpleService;
public void fooFunc() {
// here I need some magic to get value of attr2.prop
sammpleService.setAttr(attr2);
}
}
Can you tell if it is possible an how? Thanks
If I understand properly your question, then this should help:
#Service
public class SuperHotServiceImpl {
#Autowired
private SampleConfig sammpleConfig;
public void fooFunc() {
System.out.println(sampleConfig.getAttr2());
}
}
Supposed that SampleConfig is annotated as #Component and that you provide the getter.
I have a Spring application and in it I do not use xml configuration, only Java Config. Everything is OK, but when I try to test it I faced problems with enabling autowiring of components in the tests. So let's begin. I have an interface:
#Repository
public interface ArticleRepository extends CrudRepository<Page, Long> {
Article findByLink(String name);
void delete(Page page);
}
And a component/service:
#Service
public class ArticleServiceImpl implements ArticleService {
#Autowired
private ArticleRepository articleRepository;
...
}
I don't want to use xml configurations so for my tests I try to test ArticleServiceImpl using only Java Configuration. So for the test purpose I made:
#Configuration
#ComponentScan(basePackages = {"com.example.core", "com.example.repository"})
public class PagesTestConfiguration {
#Bean
public ArticleRepository articleRepository() {
// (1) What to return ?
}
#Bean
public ArticleServiceImpl articleServiceImpl() {
ArticleServiceImpl articleServiceImpl = new ArticleServiceImpl();
articleServiceImpl.setArticleRepository(articleRepository());
return articleServiceImpl;
}
}
In articleServiceImpl() I need to put instance of articleRepository() but it is an interface. How to create new object with new keyword? Is it possible without creating xml configuration class and enable Autowiring? Can autowired be enabled when using only JavaConfigurations during testing?
This is what I have found is the minimal setup for a spring controller test which needs an autowired JPA repository configuration (using spring-boot 1.2 with embedded spring 4.1.4.RELEASE, DbUnit 2.4.8).
The test runs against a embedded HSQL DB which is auto-populated by an xml data file on test start.
The test class:
#RunWith( SpringJUnit4ClassRunner.class )
#ContextConfiguration( classes = { TestController.class,
RepoFactory4Test.class } )
#TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class } )
#DatabaseSetup( "classpath:FillTestData.xml" )
#DatabaseTearDown( "classpath:DbClean.xml" )
public class ControllerWithRepositoryTest
{
#Autowired
private TestController myClassUnderTest;
#Test
public void test()
{
Iterable<EUser> list = myClassUnderTest.findAll();
if ( list == null || !list.iterator().hasNext() )
{
Assert.fail( "No users found" );
}
else
{
for ( EUser eUser : list )
{
System.out.println( "Found user: " + eUser );
}
}
}
#Component
static class TestController
{
#Autowired
private UserRepository myUserRepo;
/**
* #return
*/
public Iterable<EUser> findAll()
{
return myUserRepo.findAll();
}
}
}
Notes:
#ContextConfiguration annotation which only includes the embedded TestController and the JPA configuration class RepoFactory4Test.
The #TestExecutionListeners annotation is needed in order that the subsequent annotations #DatabaseSetup and #DatabaseTearDown have effect
The referenced configuration class:
#Configuration
#EnableJpaRepositories( basePackageClasses = UserRepository.class )
public class RepoFactory4Test
{
#Bean
public DataSource dataSource()
{
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType( EmbeddedDatabaseType.HSQL ).build();
}
#Bean
public EntityManagerFactory entityManagerFactory()
{
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl( true );
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter( vendorAdapter );
factory.setPackagesToScan( EUser.class.getPackage().getName() );
factory.setDataSource( dataSource() );
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
public PlatformTransactionManager transactionManager()
{
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory( entityManagerFactory() );
return txManager;
}
}
The UserRepository is a simple interface:
public interface UserRepository extends CrudRepository<EUser, Long>
{
}
The EUser is a simple #Entity annotated class:
#Entity
#Table(name = "user")
public class EUser
{
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
#Max( value=Integer.MAX_VALUE )
private Long myId;
#Column(name = "email")
#Size(max=64)
#NotNull
private String myEmail;
...
}
The FillTestData.xml:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<user id="1"
email="alice#test.org"
...
/>
</dataset>
The DbClean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<user />
</dataset>
If you're using Spring Boot, you can simplify these approaches a bit by adding #SpringBootTest to load in your ApplicationContext. This allows you to autowire in your spring-data repositories. Be sure to add #RunWith(SpringRunner.class) so the spring-specific annotations are picked up:
#RunWith(SpringRunner.class)
#SpringBootTest
public class OrphanManagementTest {
#Autowired
private UserRepository userRepository;
#Test
public void saveTest() {
User user = new User("Tom");
userRepository.save(user);
Assert.assertNotNull(userRepository.findOne("Tom"));
}
}
You can read more about testing in spring boot in their docs.
You cant use repositories in your configuration class because from configuration classes it finds all its repositories using #EnableJpaRepositories.
So change your Java Configuration to:
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("com.example")
#EnableJpaRepositories(basePackages={"com.example.jpa.repositories"})//Path of your CRUD repositories package
#PropertySource("classpath:application.properties")
public class JPAConfiguration {
//Includes jpaProperties(), jpaVendorAdapter(), transactionManager(), entityManagerFactory(), localContainerEntityManagerFactoryBean()
//and dataSource()
}
If you have many repository implementation classes then create a separate class like below
#Service
public class RepositoryImpl {
#Autowired
private UserRepositoryImpl userService;
}
In your controller Autowire to RepositoryImpl and from there you can access all your repository implementation classes.
#Autowired
RepositoryImpl repository;
Usage:
repository.getUserService().findUserByUserName(userName);
Remove #Repository Annotation in ArticleRepository and ArticleServiceImpl should implement ArticleRepository not ArticleService.
What you need to do is:
remove #Repository from ArticleRepository
add #EnableJpaRepositories to PagesTestConfiguration.java
#Configuration
#ComponentScan(basePackages = {"com.example.core"}) // are you sure you wanna scan all the packages?
#EnableJpaRepositories(basePackageClasses = ArticleRepository.class) // assuming you have all the spring data repo in the same package.
public class PagesTestConfiguration {
#Bean
public ArticleServiceImpl articleServiceImpl() {
ArticleServiceImpl articleServiceImpl = new ArticleServiceImpl();
return articleServiceImpl;
}
}