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.
Related
Can anyone tell me what is the error in this program and how to correct the error? I have given proper annotation and still getting errors.
I need help fixing this error I get when trying to deploy . Why isn't the Car bean being defined? Am I missing something in my web.xml or do I have to map the customerService somehow? I am using annotations for mapping. any help would be much appreciated. Here is the error log entry from the localhost log:
App.java
package om.venkatesh.omshakthi;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context=new ClassPathXmlApplicationContext("Spring.xml");
Car obj=(Car)context.getBean("car");
obj.drive();
}
}
Car.java
package om.venkatesh.omshakthi;
import org.springframework.stereotype.Component;
#Component
public class Car implements Vehicle{
public void drive()
{
System.out.println("Car");
}
}
Vehicle.java
package om.venkatesh.omshakthi;
public interface Vehicle {
void drive();
}
Spring.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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="tyre" class="om.venkatesh.omshakthi.Tyre">
</bean>
</beans>
Without xml you can do it like this:
Create config class:
#Configuration
public class AppConfig {
#Bean
public Car car() {
return new Car();
}
}
Main class:
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
Car car = (Car) ctx.getBean("car");
car.drive();
}
}
Spring.xml has no bean with id "car" (although there is one for "tyre")
You need to define your bean in XML
<bean id="car" class="om.venkatesh.omshakthi.Car">
You don`t need #Component annotation when you use ClassPathXmlApplicationContext.
Just define a Car bean in your xml:
<bean id="car" class="om.venkatesh.omshakthi.Car">
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.
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.
This question already has answers here:
Using Spring 3 autowire in a standalone Java application
(5 answers)
Closed 9 years ago.
Is there a way to run Spring application configured by annotation, directly from main method?
I'm still getting NullPointerException runing code below. Note that I'm not using SpringMVC and when I'm using beans defined inside context.xml, injected inside main method by context.getBean method, all code works perfect (without error) - but I just wondering if it is a way to manage runing this only with annotations?
//IElem.java
package com.pack.elem;
public interface IElem {
public abstract String sayHello();
}
//Elem.java
package com.pack.elem;
import org.springframework.stereotype.Component;
#Component
public class Elem implements IElem{
#Override
public String sayHello() {
return ("Hello from Elem class object");
}
}
//RunElem.java
package com.pack.elem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class RunElem {
#Autowired
private IElem elem;
public void runHello(){
System.out.println(elem.sayHello());
}
}
//Main.java
package com.pack.main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.pack.elem.RunElem;
public class Main {
#Autowired
private RunElem runelem;
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("/META-INF/application-context.xml");
new Main().runRun();
}
private void runRun(){
runelem.runHello();
}
}
<!--/META-INF/application-context.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.pack"/>
</beans>
Put simply, Spring is autowiring if it is the one instantiating the bean. So you have to use getBean(). If you want to use annotations only, something like this should work:
#Component
public class Main {
#Autowired
private RunElem runelem;
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("/META-INF/application-context.xml");
Main mainBean = context.getBean(Main.class);
mainBean.runRun();
}
private void runRun(){
runelem.runHello();
}
}
Alternatively you can autowire an existing bean as shown below, but this is not a recommended Spring usage:
public class Main {
#Autowired
private RunElem runelem;
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("/META-INF/application-context.xml");
Main mainBean = new Main();
context.getAutowireCapableBeanFactory().autowireBean(mainBean);
mainBean.runRun();
}
private void runRun(){
runelem.runHello();
}
}
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.