Spring 注入有构造注入和设值注入。
常用设置注入。
package com.shpun.dao 包下
BaseDao
package com.shpun.dao;
public interface BaseDao {
void connectSql();
void closeSql();
}
BaseDaoImpl
package com.shpun.dao;
public class BaseDaoImpl implements BaseDao {
@Override
public void connectSql() {
System.out.println("connect mysql");
}
@Override
public void closeSql() {
System.out.println("close mysql");
}
}
CustomerDao
package com.shpun.dao;
public interface CustomerDao {
void queryAllCustomers();
}
CustomerDaoImpl
package com.shpun.dao;
public class CustomerDaoImpl implements CustomerDao {
private BaseDao baseDao;
// 设值注入
public void setBaseDao(BaseDao baseDao) {
this.baseDao = baseDao;
}
@Override
public void queryAllCustomers() {
baseDao.connectSql();
System.out.println("queryAllCustomers success");
baseDao.closeSql();
}
}
package com.shpun.service 下
ActivityService
package com.shpun.service;
public interface ActivityService {
void joinActivity();
}
ActivityServiceImpl
package com.shpun.service;
public class ActivityServiceImpl implements ActivityService {
private CustomerDao customerDao;
// 构造注入
public ActivityServiceImpl(CustomerDao customerDao){
this.customerDao = customerDao;
}
@Override
public void joinActivity() {
System.out.println("查询愿意活动客户 : ");
customerDao.queryAllCustomers();
System.out.println("以上客户参加活动");
}
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-config.xml");
ActivityServiceImpl activityServiceImpl = context.getBean("activityServiceImpl",ActivityServiceImpl.class);
activityServiceImpl.joinActivity();
}
}
spring-config.xml
<bean id="baseDaoImpl" class="com.shpun.dao.BaseDaoImpl"/>
<bean id="customerDaoImpl" class="com.shpun.dao.CustomerDaoImpl">
<!-- CustomerDaoImpl中依赖BaseDaoImpl,使用标签property进行设值注入
name要和CustomerDaoImpl中要一致 ref为要注入的Bean
-->
<property name="baseDao" ref="baseDaoImpl"/>
</bean>
<bean id="activityServiceImpl" class="com.shpun.service.ActivityServiceImpl">
<!-- ActivityServiceImpl依赖CustomerDaoImpl,进行构造注入 -->
<constructor-arg name="customerDao" ref="customerDaoImpl"/>
</bean>
显示结果
查询愿意活动客户 :
connect mysql
queryAllCustomers success
close mysql
以上客户参加活动
若A类需要依赖其他类B,C,D,则在类A内实现B,C,D的set方法,在配置文件中加property,进行设值注入;或在构造器中进行构造注入。
要使用注解的方式,需要在配置文件加上:
<!--
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
-->
<!-- 自动扫描con.shpun以及子包下所有的Bean -->
<context:component-scan base-package="com.shpun"></context:component-scan>
BaseDaoImpl 类定义上加上 @Repository
CustomerDaoImpl 类定义上加上 @Repository ,set方法上加上@Autowired
ActivityServiceImpl 类定义上加上 @Service,构造器上加上@Autowired
网友评论