package com.xueyou.demo;
import org.springframework.stereotype.Component;
@Component
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
package org.xueyou.demo;
import org.springframework.stereotype.Component;
@Component
public class Body {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private int id;
}
4、在配置类App中,添加ComponentScan
需要注意的是,这里需要指定扫描的包
package com.xueyou.demo;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Hello world!
*/
@Configuration
@ComponentScan(basePackages = {"org.xueyou.demo","com.xueyou.demo"})
public class App {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
5、新建一个测试类
package com.xueyou.demo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.xueyou.demo.Body;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = App.class)
public class Springtest {
@Autowired
private Body body;
@Autowired
private Person person;
@Test
public void testBodyIsNull(){
Assert.assertNotNull(body);
}
@Test
public void testPersonIsNull(){
Assert.assertNotNull(person);
}
}