一.在applicationContext.xml配置中指定要扫描的包
<context:component-scan base-package="com.lg"/>
二:创建PersonDao类并添加注解
dao层的类使用@Repository注解
@Repository
public class PersonDao {
public Person find(Person p) {
if("lglg".equals(p.getUsername())&&"12345".equals(p.getPassword())){
return p;
}else{
return null;
}
}
}
三:创建PersonService类并注入PersonDao
service层使用@service注解
@Service
public class PersonService {
@Autowired
PersonDao personDao ;
public boolean login(Person p) {
Person person = personDao.find(p);
return person!=null;
}
}
编写测试类
使用junit测试是否注入成功
public class Test1{
private ClassPathXmlApplicationContext context;
@Before
public void init(){
context=new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void test(){
PersonService personService = (PersonService) context.getBean("personService");
Person p = new Person();
p.setUsername("jack");
p.setPassword("12345");
if (personService.login(p)){
System.out.println("登录成功");
}else {
System.out.println("登录失败");
}
}
}