一、在resource目录里创建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>
测试:
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依赖注入
<?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">
<!--定义一个java对象,当spring启动的时候就会自动初始化-->
<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
和:
<!--在当前的配置之中采用Annotation的注解方式进行定义-->
<context:annotation-config/>
<!--定义扫描包,此包中定义的所有的程序类支持Annotation-->
<context:component-scan base-package="com.xxxxx"/>
加入后如下:
四、在java文件中增加Annotation
目录格式如下
@Service注解服务层
@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) {
}
}
四、测试(Junit)
ICheckService service = context.getBean("checkServiceImpl", CheckServiceImpl.class);
CheckItem checkItem = new CheckItem();
checkItem.setTitle("test title");
checkItem.setDetail("test detail");
service.addCheckItem(checkItem);
网友评论