I have a simple Spring Boot web project, right from a template:
#SpringBootApplication
#RestController
public class HelloWorldRestApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldRestApplication.class, args);
Performer p = new Performer();
p.perform();
}
}
I have a test to ensure autowiring works, and in fact it does in this test class (examples come from Spring in Action, 4th):
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
#Autowired
private CDPlayer cdp;
#Test
public void cdShouldNotBeNull(){
assertNotNull(cdp);
}
}
and:
public class Performer {
#Autowired
private CDPlayer cdp;
public void perform(){
System.out.println(cdp);
cdp.play();
}
public CDPlayer getCdp() {
return cdp;
}
public void setCdp(CDPlayer cdp) {
this.cdp = cdp;
}
}
and:
#Component
public class CDPlayer{
public void play(){
System.out.println("play");
}
}
config:
#Configuration
#ComponentScan
public class CDPlayerConfig {
}
However, it doesnt work in HelloWorldRestApplication, I get null.
Adding #ContextConfiguration(classes=CDPlayerConfig.class) doesn't help.
What do I miss?
Try enabling #ComponentScan your packages in your main class and get Performer class instance from ApplicationContext as below:
#SpringBootApplication
#RestController
#ComponentScan({“package.name.1”,”package.name.2”})
public class HelloWorldRestApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(HelloWorldRestApplication.class, args);
Performer p = ctx.getBean(Performer.class);//get the bean by type
p.perform();
}
}
Related
Application.java
#SpringBootApplication(scanBasePackages = {"ru.pcask.clients",
"ru.pcask.activities"
})
#EntityScan(value={"ru.pcask.clients",
"ru.pcask.activities"})
#EnableJpaRepositories(value={"ru.pcask.clients",
"ru.pcask.activities"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
"ru.pcask.clients" seems to be a constant. But I don't know how to organize it?
I tried like this:
Constants.java
#Configuration
public class Constants {
private static final String CLIENT = "ru.pcask.clients";
#Bean
public String getClientConst() {
return this.CLIENT;
}
}
But this seems to be a garbage. I don't even know how to use it in #SpringBootApplication.
I have a testng+spring suite with parallel option set to Tests. I would like to have each <test> have it's own ApplicationContext. So each <test> thread will have their own set of beans. I am able to initialise the ApplicationContext but the beans are not getting autowired and I am getting nullpointer exception when I am trying to access the bean. Please find my code below,
AppTest.class
#ComponentScan(basePackages = "org.comp.automation")
public class AppTest extends AbstractTestNGSpringContextTests{
#BeforeTest
public void intialise() throws Exception{
ApplicationContext context = new AnnotationConfigApplicationContext(BeanTwo.class);
}
#Autowired
public CommonBean commonBean;
#Autowired
public BeanTwo beanTwo;
#Parameters(value={"param"})
#Test
public void shouldAnswerWithTrue(String param) {
System.out.println(commonBean.STRING_CHECK);
commonBean.createCommonBeanObject(param);
System.out.println("Checking the bean values now...");
assertTrue( true );
}
}
CommonBean.class
#Component
public class CommonBean {
public String commonBeanValue;
public String STRING_CHECK = "Hello!!";
public void createCommonBeanObject(String param){
commonBeanValue = param;
}
public void printParamValue(){
System.out.println(commonBeanValue);
}
}
BeanTwo.class
#Component
public class BeanTwo{
public void printBeanTwo(){
System.out.println("Bean Two!!");
}
}
Can someone help me with this and point me in the right direction?
I am new to spring boot testing. I have error related to loading application context when I am trying to test some methods of below AwsTestsExtractor class.
Error message:
Field awsTestsExtractor in com.silvio.me.Prototype required a bean of
type 'com.silvio.me.AwsTestsExtractor' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.silvio.me.AwsTestsExtractor' in
your configuration.
Code:
#Component
public class AwsTestsExtractor extends TestsExtractor {
#Autowired
private ExaminationRepository examinationRepository;
public AwsTestsExtractor() { }
...
...
private String getTestDbRef(String description) {
ArrayList<Examination> strArr = new ArrayList<>(examinationRepository.customQuery(description));
if(strArr.size() > 0)
return strArr.get(0).getName();
else
return null;
}
}
#SpringBootApplication
public class Prototype implements CommandLineRunner {
#Autowired
private AwsTestsExtractor awsTestsExtractor;
public static void main(String[] args) {
SpringApplication.run(Prototype.class, args);
}
#Override
public void run(String... args) throws Exception {
String document="src/main/resources/test2.jpg";
awsTestsExtractor.extract(document);
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
#RunWith(SpringRunner.class)
#TestPropertySource(locations = "classpath:application-integrationtest.properties")
#DataMongoTest
public class AwsTestsExtractorTest {
#Autowired
private MongoTemplate mongoTemplate;
#Autowired
private AwsTestsExtractor awsTestsExtractor;
#Before
public void setUp() {
mongoTemplate.save(new Examination("terefere"));
}
#Test
public void getTestDbRefTest() {
assertTrue(ReflectionTestUtils.invokeMethod(awsTestsExtractor, "getTestDbRef","terefere" ).equals(true));
}
}
I suppose I make some fundamental mistake, any help appreciated.
I have below project structure
My code files are as belows
DemoApplication.java
#SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
CarListGrabber grabber = new CarListGrabber();
grabber.grabCarsWithName("Test");
}
}
NewCarRepository.java
#Repository
public interface NewCarRepository extends CrudRepository<NewCar, Long> {
}
NewCar.java
#Entity
#Table(name = "new_car_details")
public class NewCar {
// member variables with default constructor
}
CarListGrabber.java
#Service
public class CarListGrabber {
#Autowired
private NewCarRepository newCarRepository;
// someOtherStuff
}
Even though I have used annotations #Repository, #Service I am getting null repository object in service.
You are instantiating a new CarListGrabber with:
CarListGrabber grabber = new CarListGrabber();
it will not make injections you need to inject also your grabber, like:
#Autowired
CarListGrabber grabber;
I have following repository which extends jpa repositroy and also have an implementation class where i have autowired this.
#Repository
public interface ProjectDAO extends CrudRepository<Project, Integer> {}
#Service
public class ProjectServiceImpl {
#Autowired private ProjectDAO pDAO;
public void save(Project p) { pDAO.save(p); } }
Now i have one Application.java class
Class Application{
public static void main(String..s){
// I need a way to call a method of repository
}
}
configuration file
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories
#PropertySource("file:/Users/abc/Documents/application.properties")
public class PersistenceContext {
#Autowired
Environment environment;
So how do we call this from main in case i dont to use any web based controller?
This is a way:
class Application {
public static void main(String[] s){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersistenceContext.class);
ProjectDAO dao = applicationContext.getBean(ProjectDAO.class);
}
}
Edit:
class Application {
public static void main(String[] s){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersistenceContext.class);
ProjectServiceImpl service = applicationContext.getBean(ProjectServiceImpl.class);
}
}