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.
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'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.
I'm trying to write tests for an application that uses #RefreshScope. I would like to add a test that actually changes out properties and asserts that the application responds correctly. I have figured out how to trigger the refresh (autowiring in RefreshScope and calling refresh(...)), but I haven't figured out a way to modify the properties. If possible, I'd like to write directly to the properties source (rather than having to work with files), but I'm not sure where to look.
Update
Here's an example of what I'm looking for:
public class SomeClassWithAProperty {
#Value{"my.property"}
private String myProperty;
public String getMyProperty() { ... }
}
public class SomeOtherBean {
public SomeOtherBean(SomeClassWithAProperty classWithProp) { ... }
public String getGreeting() {
return "Hello " + classWithProp.getMyProperty() + "!";
}
}
#Configuration
public class ConfigClass {
#Bean
#RefreshScope
SomeClassWithAProperty someClassWithAProperty() { ...}
#Bean
SomeOtherBean someOtherBean() {
return new SomeOtherBean(someClassWithAProperty());
}
}
public class MyAppIT {
private static final DEFAULT_MY_PROP_VALUE = "World";
#Autowired
public SomeOtherBean otherBean;
#Autowired
public RefreshScope refreshScope;
#Test
public void testRefresh() {
assertEquals("Hello World!", otherBean.getGreeting());
[DO SOMETHING HERE TO CHANGE my.property TO "Mars"]
refreshScope.refreshAll();
assertEquals("Hello Mars!", otherBean.getGreeting());
}
}
You could do this (I assume you mistakenly omitted the JUnit annotations at the top of your sample, so I'll add them back for you):
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
public class MyAppIT {
#Autowired
public ConfigurableEnvironment environment;
#Autowired
public SomeOtherBean otherBean;
#Autowired
public RefreshScope refreshScope;
#Test
public void testRefresh() {
assertEquals("Hello World!", otherBean.getGreeting());
EnvironmentTestUtils.addEnvironment(environment, "my.property=Mars");
refreshScope.refreshAll();
assertEquals("Hello Mars!", otherBean.getGreeting());
}
}
But you aren't really testing your code, only the refresh scope features of Spring Cloud (which are already tested extensively for this kind of behaviour).
I'm pretty sure you could have got this from the existing tests for refresh scope as well.
Properties used in the application must be variables annotated with #Value. These variables must belong to a class that is managed by Spring, like in a class with the #Component annotation.
If you want to change the value of the properties file, you can set up different profiles and have various .properties files for each profile.
We should note that these files are meant to be static and loaded once, so changing them programmatically is sort of out of the scope of ther intended use. However, you could set up a simple REST endpoint in a spring boot app that modifies the file on the host's file system (most likely in the jar file you are deploying) and then calls Refresh on the original spring boot app.
I am new to Spring. I have at work in spring-config.xml this :
<bean id="statusEmailSender" class="my.package.email.StatusEmailSenderImpl">
<property name="mailSender" ref="mailSender"/>
<property name="templateMessage" ref="templateMessage"/>
</bean>
In some classes already defined I see something like this:
#Autowired
private StatusEmailSender statusEmailSender;
And it works. When I do it in my own class, I get a NullPointerException.
I know the reason: I am creating my class with new():
return new EmailAction(config,logger);
My class looks like this:
public class EmailAction{
#Autowired
StatusEmailSender statusEmailSender;
public EmailAction(...)
{
...
}
}
Do you know how I can get around this? This is legacy code, and it's extremely difficult to get around the new EmailAction() call.
You want use a spring bean inside a non-spring class(legacy code). In order to do that you need to make the Spring's ApplicationContext (which holds BeanFactory where spring beans are residing) available to legacy code.
For that you need to create a spring bean something like:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContext implements ApplicationContextAware {
private static ApplicationContext context;
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
public static ApplicationContext getApplicationContext() {
return context;
}
}
and define this bean inside your Spring configuration file (or if you are using annotation driven, annotate bean with #Component)
<bean id="springContext" class="com.util.SpringContext />
Since SpringContext exposes a static method, the legacy code can access it.for example if the legacy code needs spring bean EmailAction, call like:
EmailAction emailAction= (EmailAction)SpringContext.getApplicationContext.getBean(EmailAction.class);
now the emailAction will contain all its dependencies set.
Why don't you just autowire your EmailAction class when you need it?
EmailAction.java:
#Component
public class EmailAction{
// ...
}
WhereYouNeedIt.java:
public class WhereYouNeedIt{
#Autowired
EmailAction emailAction;
// access emailAction here
}
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.