I'm implemented a little service based on Spring. I would like to autowire the class Demo within the DemoController. Therefore I defined the values for it within the beans.xml file. It seems like spring finds the bean because everything is compiling. But the return value of the service looks like this:
{"valueUno":0,"valueDue":null}
DemoApplication:
#SpringBootApplication
#ComponentScan({"com"})
#EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Demo:
#Component
public class Demo {
private int valueUno;
private String valueDue;
//getter, setter....
}
DemoController:
#RestController
public class DemoController {
#Autowired
private Demo demo;
#RequestMapping(
value = "/welcome",
method = RequestMethod.GET
)
public HttpEntity<Demo> getMessage() {
return new HttpEntity<Demo>(this.demo);
}
}
beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="demo" class="com.example.demo.Demo">
<property name="valueUno" value="50"></property>
<property name="valueDue" value="Hello"></property>
</bean>
</beans>
Everything is inside one package. I dont get it...
You have annotated Demo as a #Component. Therefore, Spring instantiates a bean of this class using its default constructor during the component scan (you have enabled it with #ComponentScan({"com"})), and then injects (autowires) it into DemoController. So, the autowired bean not the one defined in beans.xml.
There are 2 ways to solve the issue:
1) If you want to go with XML configuration, remove #Component from Demo class, and add #ImportResource("classpath:beans.xml") annotation to your Controller class.
2) If you want to go with JavaConfig (annotations), you would need to add separate class like this:
#Configuration
public class MyConfiguration {
#Bean
public Demo demo() {
return new Demo(50, "Hello"); // or initialize using setters
}
}
...and add #Import(MyConfiguration.class) annotation to your Controller class, and remove #Component from Demo class.
As a solution to what #PresentProgrammer said, you can move your XML configuration to a Java configuration as following:
#Bean
public Demo demo() {
Demo demo = new Demo();
demo.setValueUno(50);
demo.setValueDue("Hello");
return demo;
}
You can add this configuration directly to the DemoApplication class or to a configuration class:
#Configuration
public class BeanConfiguration {
//Bean Configurations
}
For further details, you can read Java-based container configuration Spring documentation.
Related
I want to test a class that simple shutdown the application:
#Component
public class ShutdownManager {
#Autowired
private ApplicationContext applicationcontext;
public int shutdown(int returnCode) {
return SpringApplication.exit(applicationcontext, () -> returnCode);
}
}
The test case I created is this:
public class ShutdownManagerTest {
#Test
public void should_shutdown_gracefully() {
SpringApplication app = new SpringApplication(TestClass.class);
ConfigurableApplicationContext context = app.run();
ShutdownManager shutdownManager = (ShutdownManager)context.getBean("shutdownManager");
int result = shutdownManager.shutdown(10);
assertThat(result).isEqualTo(10);
}
#SpringBootApplication
#ImportResource("classpath:/core/shutdownmanagertest.xml")
private static class TestClass {
public TestClass() {
}
public static void main(String[] args) {
}
}
}
My shutdownmanagertest.xml contains only one bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="shutdownManager" class="com.mycodebase.ShutdownManager" />
</beans>
However, when I run this, it complains that:
Field myOtherService in com.mycodebase.MyTask required a bean of type 'com.mycodebase.MyOtherService ' that could not be found.
The class MyTask is in the same package of the ShutdownManager which contains a field myOtherService which has an #Autowire annocation. But it is not defined in my test xml which contains just one bean.
Can someone help me understand why it tries to resolve a bean that is not in the context?
It's doing that because that's how #SpringBootApplication works.
#SpringBootApplication:
This is a convenience annotation that is equivalent to declaring #Configuration, #EnableAutoConfiguration and #ComponentScan.
#ComponentScan
If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
So everything in the same or a subpackage of ShutdownManagerTest is being picked up.
I am trying to create a new starter. I have a business module, say ProjectManager, that contains some classes annotated with #Component. Following the tutorial, I created an autoconfigure module, it contains an AutoConfiguration class. Firstly, I tried to use #ComponentSan to find the beans in my business module.
#ComponentScan(value = {"com.foo.project"})
#ConditionalOnClass({Project.class})
#Configuration
public class ProjectAutoConfiguration {
....
}
But it doesn't work. I have to add additional configuration class as below:
#Configuration
#ComponentScan(value = {"com.foo.project"})
#MapperScan(value = {"com.foo.project"})
public class ProjectConfig {
}
And then import it into AutoConfiguration class like below:
#Import(ProjectConfig.class)
#ConditionalOnClass({Project.class})
#Configuration
public class ProjectAutoConfiguration {
....
}
That works. But according to the spring doc.
auto-configuration is implemented with standard #Configuration classes
So my question is, Why #ComponentScan doesn't work here ? Did I make something wrong? Or it is by design ?
you have to use the compentscan annotation into the main class. Here a sample code:
#SpringBootApplication
#ComponentScan("com.foo.project")
public class MainApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MainApplication.class);
}
public static void main(String[] args) {
new MainApplication().configure(new SpringApplicationBuilder(MainApplication.class)).run(args);
}
}
Cheers
Automatic everything requires the Application class (annotated with #SpringBootApplication) to be in a "higher" package than the components you want to scan.
Use:
package com.example.foo;
for your application and put components in a package like:
package com.example.foo.entities;
See also https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html
Can you try with following?
#ConditionalOnClass({Project.class})
#Configuration
#EnableAutoConfiguration
#ComponentScan(value = {"com.foo.project"})
public class ProjectAutoConfiguration {
....
}
I was developing a SDK project. It needs the application which depends on the SDK to scan for beans beneath specific package in the SDK during start period.
Anotate with #ComponentScan on autowire configuration class doesn't take effect.
Then I am trying to use #Import annotation to import a class implemented interface ImportBeanDefinitionRegistrar(Interface to be implemented by types that register additional bean definitions when processing #Configuration classes. Useful when operating at the bean definition level (as opposed to #Bean method/instance level) is desired or necessary).
Within ImportBeanDefinitionRegistrar implementation class, I register a class annotated with #ComponentScan as bean. Run application again, it works as expected.
Codes below:
AutoConfiguration Class:
#Configuration
#Import(TestConfigRegistar.Registrar.class)
public class TestClientAutoCofiguration {
}
Registar class:
public class TestConfigRegistar {
public static class Registrar implements ImportBeanDefinitionRegistrar {
private static final String BEAN_NAME = "componentScanConfig";
#Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata,
BeanDefinitionRegistry registry) {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(ComponentScanConfig.class);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
beanDefinition.setSynthetic(true);
registry.registerBeanDefinition(BEAN_NAME, beanDefinition);
}
}
}
Class with #ComponentScan annotation
// Leave an empty value of #ComponentScan will let spring scan
// current class package and all sub-packages
#ComponentScan
public class ComponentScanConfig {
}
I believe that the point is that beans annotated with #ComponentScan must be defined at definition level (as opposed to #Bean method/instance level). Please correct me if I'm wrong, Thanks.
So, with Spring, I prefer xml over annotation. It's just a personal preference, I like having the xml docs unifying my spring config data.
Anyway, I'm working on a JUnit test case for database access. My first time using the spring-test library. I'm trying to use dependency injection to inject the StudentDao bean into this class below:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration ({"classpath:/test-context.xml"})
public class StudentDaoTest extends TestCase {
private StudentDao studentDao;
public StudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
#Test
#Transactional
public void test(){
//This ends up printing null, identifying the problem
if(studentDao == null){
System.out.println("Null");
}
Student student = new Student();
student.setFirstName("First");
studentDao.insertStudent(student);
}
}
The thing is, as you can guess from the comment, is this isn't working. The test-context.xml file starts up, and the other context file it imports also starts up, as I can see from the log, so it's not that the program can't find the file. Somehow the xml doc that I have is just not configuring the bean properly.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="data-context.xml"/>
<bean id="studentDaoTest" class="io.craigmiller160.schedule.persist.StudentDaoTest">
<property name="studentDao" ref="studentDao"/>
</bean>
I discovered that if I used the #Autowired annotation on studentDao it does work. The thing is, I don't use annotations anywhere else in the program, and I want to maintain consistency. Honestly, I would prefer to avoid using #ContextConfiguration too, but I don't think I'll be able to do that.
So, I'm looking for help making this injection work with just xml. I know, I'm being picky, but I like my consistency, as I said.
Thanks in advance.
PS. the full filepath of the files is:
StudentDaoTest: src/test/java/io/myname/schedule/persist/StudentDaoTest
test-context.xml: src/test/resources/test-context.xml
If you don't want to use Spring annotations why use them ?
public class MyTest {
private ConfigurableApplicationContext context;
#Before
public void initApplicationContext() {
context = new ClassPathXmlApplicationContext("...");
}
#After
public void closeApplicationContext() {
if (context != null) {
context.close();
context = null;
}
}
#Test
public void test() {
context.getBean(Object.class);
// ...
}
}
Inject application context and work with it as you like:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration ({"classpath:/test-context.xml"})
public class StudentDaoTest extends TestCase {
#Autowired
private ApplicationContext ctx;
Actually the definition of the studentDaoTest bean has no effect on the test just because there is no such functional in the testing framework.
i am really confused with spring annotations.
where to use # Autowired, where class is # Bean or # Component,
i understand we cannot use
Example example=new Example("String");
in Spring
but how alone
#Autowired
Example example;
will solve the purpose?
what about Example Constructor ,how spring will provide String value to Example Constructor?
i went through one of the article but it does not make much sense to me.
it would be great if some one can give me just brief and simple explanation.
Spring doesn't say you can't do Example example = new Example("String"); That is still perfectly legal if Example does not need to be a singleton bean. Where #Autowired and #Bean come into play is when you want to instantiate a class as a singleton. In Spring, any bean you annotate with #Service, #Component or #Repository would get automatically registered as a singleton bean as long as your component scanning is setup correctly. The option of using #Bean allows you to define these singletons without annotating the classes explicitly. Instead you would create a class, annotate it with #Configuration and within that class, define one or more #Bean definitions.
So instead of
#Component
public class MyService {
public MyService() {}
}
You could have
public class MyService {
public MyService() {}
}
#Configuration
public class Application {
#Bean
public MyService myService() {
return new MyService();
}
#Autowired
#Bean
public MyOtherService myOtherService(MyService myService) {
return new MyOtherService();
}
}
The trade-off is having your beans defined in one place vs annotating individual classes. I typically use both depending on what I need.
You will first define a bean of type example:
<beans>
<bean name="example" class="Example">
<constructor-arg value="String">
</bean>
</beans>
or in Java code as:
#Bean
public Example example() {
return new Example("String");
}
Now when you use #Autowired the spring container will inject the bean created above into the parent bean.
Default constructor + #Component - Annotation is enough to get #Autowired work:
#Component
public class Example {
public Example(){
this.str = "string";
}
}
You should never instantiate a concrete implementation via #Bean declaration. Always do something like this:
public interface MyApiInterface{
void doSomeOperation();
}
#Component
public class MyApiV1 implements MyApiInterface {
public void doSomeOperation() {...}
}
And now you can use it in your code:
#Autowired
private MyApiInterface _api; // spring will AUTOmaticaly find the implementation
I am using Spring autoscan components in my testing framework.
Autowired works fine in all classes except in class which extends Junit Testwatcher.
The class where I extend Junit testwatcher is:
#Component
public class PrintTrace extends TestWatcher{//this class overrides pass and fail
//methods in Testwatcher
#Autowired
private HTMLLogger htmlLogger //this is null all the time. it works in
//other classes
}
My Base class looks like:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:beans.xml"})
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class })
public class YahooTestSetUp {
public static WebDriver driver;
#Rule
public PrintTrace printTrace = new PrintTrace();
#Autowired
private HTMLLogger htmlLogger;//here its working fine
}
And my xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.pilz"/>
</beans>
Please advice this is very important for me. Otherwise I should go for
singleton objects,which is not a good solution for me.
Adding more info:
Lets say i have 2 test suites which access 2 common classes HTMLLogger.class and PrintTraece.class.
Each testsuite is independent of other suite. These suites have #BeforeClass and #AfterClass
see below:
#RunWith(Suite.class)
#Suite.SuiteClasses({ AutowireClass.class})
public class YahooTestSuite extends YahooTestSetUp{
private static HTMLLogger htmlLogger;
#BeforeClass
public static void allTests() throws Exception {**//Can I use #Autowired in
static methods(no)**
htmlLogger = new HTMlLogger()
htmlLogger.createHTMLLogFile();
}
#AfterClass
public static void afterAll() throws Exception{
htmlLogger.htmlLogEnd();
}
}
and another suite is doing same for other module.
As i said before my PrintTrace.class extends Testwatcher.class(Junit rule) its look like
This class is invoked with the the rule created in baseclass.
#Component
public class PrintTrace extends TestWatcher{
private HTMLLogger htmlLogger = null;
#Override
public void starting(final Description description) {
}
#Override
public void failed(final Throwable e, final Description description) {
htmlLogger.writeFailLog();**//This is common for all suites**
//This should be same object used in suite
}
#Override
public void succeeded(final Description description) {
htmlLogger.writePassLog();//This is common for all suites
//This should be same object used in suite
}
#Override
public void finished(Description description) {
}
thanks
Why do you want to use Spring DI for JUnit rules? Your test code is not your application.
In some of the java classes, like the test cases or web-listeners, #Autowired doesn't work. You have to define the applicationContext like an object and receive beans manually.
ApplicationContext context = AnnotationConfigApplicationContext("app_context_file_path")
HTMLLogger htmlLogger = context.getBean("loggerBeanName");
Also, have a look over here - http://static.springsource.org/spring/docs/3.0.x/reference/testing.html
And google about the #Resource spring annotation.
To get the exact object you need, you should have the following configuration:
If you create a bean in the application context file, just use the id of it in the getBean(name) method. If you have it as a separate class, provide it (class) with the #Component(value) annotation and scan the package in the application context. After that use the value name of that bean(component) to get the exact object you've configured.