package junit_test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import zmj.service.interf.PersonService;
public class springTest {
@Test
public void instanceSpring() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService)ctx.getBean("personService");
personService.save();
}
}
package zmj.service.impl;
/*import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;*/
import org.springframework.beans.factory.annotation.Autowired;
import zmj.dao.interf.PersonDao;
import zmj.service.interf.PersonService;
public class PersonServiceBean implements PersonService {
/* (non-Javadoc)
* @see zmj.service.impl.PersonService#save()
*/
//@Autowired 按类型注解注入
//@Resource 先按属性名在spring配置文件中寻找,如果找不到则按类型注入
private PersonDao personDao;
private String name = "hello sun";
/*public PersonServiceBean(PersonDao personDao, String name) {
this.personDao = personDao;
this.name = name;
}*/
@Override
public void save() {
System.out.println("sava method ");
personDao.add();
System.out.println(name);
}
/**************第二种方式进行注入**************/
/*@Resource
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}*/
}
package zmj.service.interf;
/*import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;*/
public interface PersonService {
public void save();
/* public Set<String> getSet();
public String getName();
public List<String> getList();
public Properties getProperties();
public Map<String, String> getMap();*/
}
<?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" <!--这边引入命名空间context-->
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config/>
<bean id="personDao" class="zmj.dao.impl.PersonDaoBean"></bean> <!-- 外部的bean -->
<bean id="personService" class="zmj.service.impl.PersonServiceBean" >
<!--通过构造器方法注入 -->
<!-- <constructor-arg index="0" type="zmj.dao.interf.PersonDao" ref="personDao"/> 此处容易出错,应该是在PersonServiceBean中的定义的类型
<constructor-arg index="1" value="Hello Java"/> -->
</bean>
</beans>
08-09
08-09
08-09
08-09