一、在resource目錄里創(chuàng)建applicationContext.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="checkInfo" class="com.xxxx.fabu.model.CheckInfo"/>
</beans>
測(cè)試:
public class SpringTest {
@Test
public void testGetBean() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
CheckInfo checkInfo = context.getBean("checkInfo", CheckInfo.class);
if (checkInfo!=null) {
checkInfo.toString();
}
}
}
二讲仰、基于xml依賴(lài)注入
<?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">
<!--定義一個(gè)java對(duì)象慕趴,當(dāng)spring啟動(dòng)的時(shí)候就會(huì)自動(dòng)初始化-->
<bean id="checkInfo" class="com.xxxx.fabu.model.CheckInfo"/>
<bean id="user" class="com.xxxx.fabu.model.User">
<!--<property name="userName" value="姓名"/>-->
<!--<property name="role" value="1"/>-->
<constructor-arg name="userName" value="張三"/>
<constructor-arg name="role" value="1"/>
</bean>
</beans>
三、基于Annotation注入
在applicationContext中加入:
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
和:
<!--在當(dāng)前的配置之中采用Annotation的注解方式進(jìn)行定義-->
<context:annotation-config/>
<!--定義掃描包鄙陡,此包中定義的所有的程序類(lèi)支持Annotation-->
<context:component-scan base-package="com.xxxxx"/>
加入后如下:
四冕房、在java文件中增加Annotation
目錄格式如下
@Service注解服務(wù)層
@Service
public interface ICheckService {
public void addCheckItem(CheckItem checkItem);
}
@Service
public class CheckServiceImpl implements ICheckService {
@Autowired
private ICheckInfoDao iCheckInfoDao;
public void addCheckItem(CheckItem checkItem) {
iCheckInfoDao.addCheckItem(checkItem);
}
}
@Repository持久層
@Repository
public interface ICheckInfoDao {
public void addUser(User user);
public void addCheckItem(CheckItem checkItem);
public void addCheckInfo(CheckInfo checkInfo);
}
@Repository
public class CheckInfoDaoImpl implements ICheckInfoDao {
public void addUser(User user) {
System.out.println("addUser:"+user.getUserName());
}
public void addCheckItem(CheckItem checkItem) {
System.out.println("addCheckItem:title:"+checkItem.getTitle());
}
public void addCheckInfo(CheckInfo checkInfo) {
}
}
四、測(cè)試(Junit)
ICheckService service = context.getBean("checkServiceImpl", CheckServiceImpl.class);
CheckItem checkItem = new CheckItem();
checkItem.setTitle("test title");
checkItem.setDetail("test detail");
service.addCheckItem(checkItem);