create map bean with a factory in a #Configuration class - java

Trying to create a map bean with prototype scope in config class
#Configuration
public class SpringConfig {
public SpringConfig() {
}
#Bean
#Scope("prototype")
public Map<String, Composite> getCompositesMap() {
return new LinkedHashMap<String, Composite>();
}
}
But spring complains
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.eclipse.swt.widgets.Composite] found for dependency [map with value type org.eclipse.swt.widgets.Composite]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.annotation.Resource(shareable=true, mappedName=, description=, name=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=)}
How does one define a prototype map bean using annotations only (no xml)?

The error is occurring because Spring is trying to inject Composite into your method, but there is no such bean that corresponds to that class.
You can add a prototype scoped bean inside your SpringConfig class - see here.

Related

Bean is no longer being autowired after Spring 5.3 Upgrade

I upgraded my package from Spring 4.3 to Spring 5.3 which has caused a issue I am completely to solve, for some reason a Bean that is created and works under 4.3 is being created, but not wired in. The bean is being created, and the configuration has not changed, yet it doesn't work?
Bean Creation:
#Configuration
#SuppressWarnings("checkstyle:HideUtilityClassConstructor")
#Slf4j
public class EnvironmentConfig {
#Bean
public static AppEnvironmentHelper environmentHelper() throws IOException {
final AppEnvironmentHelper.Config config = new AppConfigEnvironmentHelper.Confg()
// Config object is configured
return new AppEnvironmentHelper(config);
}
}
Attempted Injection of Bean:
#Configuration
#Slf4j
public class OtherConfig {
#Value("${role}")
private String someRole;
#Value("${port}")
private String somePort;
#Autowired
private EnvironmentHelper environmentHelper;
.......
}
The class path for the bean is in the configuration, and when launching the service I see logs that indicate that EnviromentConfig is created before OtherConfig
org.springframework.beans.factory.support.DefaultListableBeanFactory: Finished creating instance of bean 'environmentHelper'
But I always get
UnsatisfiedDependencyException: Error creating bean with name 'OtherConfig': Unsatisfied dependency expressed through field 'environmentHelper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.amazon.coral.spring.EnvironmentHelper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
After it errors spring goes to clean up the beans with
Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#40db2a24: defining beans [.....,EnvironmentConfig, environmentHelper ]
Which seems to indicate to me that it is finding the bean, its creating the bean, but then when it comes to wire in enviromentHelper it doesnt find it. Ive tried naming the bean using qualifiers but that did nothing. And I wrapped the EnviromentHelper and added logs during creation of the bean and destruction, so I know the bean isnt being destroyed prematurely. Im not certain what else to try to troubleshoot further.

Spring, problem with #Value in bean constructor with prototype scope

cfg c= context.getBean(cfg.class);
First time it has to be work, but second time appear error:
No qualifying bean of type 'java.lang.String' available: expected at
least 1 bean which qualifies as autowire candidate. Dependency
annotations: {}
Why?
#Configuration
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class cfg{
public cfg(#Value("${xx}") String xx) {
System.out.println(xx);
}
}
application.properties
xx = 7
Also I found that if replace #Configuration with #Component or add (proxyBeanMethods = false) the problem goes away.
Source code
#Configuration indicates that a class declares one or more #Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime. If you want #Value to work you will need #PropertySource annotation.
If you annotate it with #Component, then it will be a fully-fledged Spring Bean on which #Value works out of the box.

Spring autowiring list of components

I have an interface:
public interface IExternalCommandExecutor {
String[] getCommandNames();
void process(String command) throws FailedOperationException;
}
And two implementations(second is similar):
#Service
public class ExecutorImpl implements IExternalCommandExecutor {
//some code...
}
And service, in which I'm using #Autowired annotation on the list of IExternalCommandExecutor:
#Service
public class ExternalCommandsService {
#Autowired
List<IExternalCommandExecutor> commandExecutors;
// other code
}
When I'm trying to run this, I'm getting this error:
NoSuchBeanDefinitionException: No qualifying bean of type
'java.util.List<com.mpcomp.entity.system.IExternalCommandExecutor>' available:
expected at least 1 bean which qualifies as autowire candidate
Which is weird behavior for Spring. As it was mentioned in this article and in the javadoc, Spring should try to autowire all elements of IExternalCommandExecutor instead of trying to find bean of type java.util.List.
If I would change List<IExternalCommandExecutor> to IExternalCommandExecutor[], error is quite similar:
NoSuchBeanDefinitionException: No qualifying bean of type
'com.mpcomp.entity.system.IExternalCommandExecutor[]' available:
expected at least 1 bean which qualifies as autowire candidate
I'm using Spring of version 4.3.8 RELEASE. Any help will be appreciated!
Edit
Interface and service are in the core module, and implementations of interface are in 'children' module which is depends on core module. When I moved service to this 'children' module, everything works fine!

SpringBootTest for DAO JUnit test

I am attempting the following unit test of a DAO.
I am unable to get the DataSource recognized.
Can I get a tip on how to resolve this?
Details below
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class EntityDaoTest {
#Autowired
protected EntityDao entityDao;
#Before
public void setup()
{
}
#Test
public void test() throws InternalServerException
{
List<Entity> entities = entityDao.list();
assert(entities.size()==0);
}
}
The relevant aspects of the DAO class are as follows
#Repository
public class EntityDao extends GenericDao<Entity>{
public EntityDao(DataSource dataSource) {/.../}
}
My src/test/resources/application.properties file is as follows
# Database
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=dbuser
spring.datasource.password=dbpass
Trace from running as JUnit test in Eclipse
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityController': Unsatisfied dependency expressed through field 'entityDao': Error creating bean with name 'entityDao' defined in file .../target/classes/hitstpa/dao/EntityDao.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type [javax.sql.DataSource] found for dependency [javax.sql.DataSource]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {};
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityDao' defined in file [/home/fmason/workspace/hitstpa/target/classes/hitstpa/dao/EntityDao.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type [javax.sql.DataSource] found for dependency [javax.sql.DataSource]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found for dependency [javax.sql.DataSource]: expected at least 1 bean which qualifies as autowire candidate for this dependency. ...`
Application structure
-src
--main
---java
----Application.java
----com
----hitstpa
-----controller
-----dao
------EntityDao.java
-----model
---resources
----application.properties
--test
---java
----hitstpa
-----dao
------EntityDaoTestDOTjava
---resources
----applicationDOTproperties
First of all for integration tests you need an integration Db with some fixed data.
Now you need to create a configuration class which will create the
integration test specific dependencies(I have named it as DbConfig
.java)
Next is add #ContextConfiguration annotation to the integration test
class and provide DbConfig.java, so that when test runs it will
create the datasource dependency and inject it to the container
Sample Code
#Configuration
public class DbConfig {
#Bean
public DataSource dataSource() {
//Create the DataSource with integration-DB properties
return dataSource;
}
}
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
#ContextConfiguration(classes=DbConfig.class)
public class EntityDaoTest {
}
For the record, I believe this is not a good unit test. This test requires that a mysql databases exists on localhost.
Anyhow, the errors suggest that the Spring Context isn't loaded correctly. When using SpringBootTest, Spring looks for the configuration using the test's package as root. So, if it's lower than your Configuration classes, it won't them.
Take a look at Spring's documentation:
The search algorithm works up from the package that contains the test
until it finds a #SpringBootApplication or #SpringBootConfiguration
annotated class. As long as you’ve structure your code in a sensible
way your main configuration is usually found.
Solution:
You can either move your tests to the same level as your SpringBoot Main class or change it to: #SpringBootTest(classes = YourSpringBootMainClass.class)

Unable to inject array list as dependency

I am creating a bean with annotations.
#Component
public class MyClass
{
#Autowired
private ArrayList<String> myFriends= new ArrayList<String>();
//Getters and setters
}
I am getting the following exception
Could not autowire field: private java.util.ArrayList com.mypackage.MyClass.myFriends; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [java.util.ArrayList] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I also tried with this
#Resource
private ArrayList<String> myFriends= new ArrayList<String>();
I am getting the following exception
No matching bean of type [java.util.ArrayList] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.annotation.Resource(shareable=true, mappedName=, description=, name=, type=class java.lang.Object, authenticationType=CONTAINER)}
Please let me know how to fix this.
In the XML file you would need to define a list.
In the XML file include the util namespace and add the following bean definition.
<util:list id="myFriends">
<value>string1</value>
<value>string2</value>
<value>string3</value>
</util:list>
You need to change the type of the variable to List<String> instead of ArrayList<String>. That will make it easier to inject and is also a better coding practice to follow. You need to add a Qualifier annotation to specify the id of the bean that needs to be injected, qualifier might not be required if you have only one such list.
#Component
public class MyClass {
#Autowired
#Qualifier("myFriends")
private List<String> myFriends= new ArrayList<String>();
//Getters and setters
}
Link to spring reference documentation for util:list
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/xsd-config.html#xsd-config-body-schemas-util-list

Categories