Spring context命名空间

(补充:之前我们使用property标签进行依赖注入的时候,Spring框架会获取property的name属性,调用set+Name();对该属性进行注入)

一个配置文件中,需要进行管理的bean的配置有很多,为了让Spring自己去加载这些Bean,实现"零配置",

引入context命名空间:

xmlns:context="http://www.springframework.org/schema/context"

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
	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-4.0.xsd
           http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util-4.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-4.0.xsd" >
     <!-- 自动扫描,配合注解来确定加载哪些类 -->     
     <context:component-scan base-package="com.langsin.dao.impl
                                           com.langsin.service"></context:component-scan>      
</beans>

Service层:

//Service注解,传入的为该类的id,如果不写默认该类的id为类名首字母小写。
@Service("roleService")
public class RoleService {	
	//@Autowired注解,告诉spring,这个变量需要自动注入(byName的方式),这种方式不需要写set方法
	@Autowired
	private RoleDao dao=null;
	
	/*public void setDao(RoleDao dao){
		this.dao=dao;
	}*/
    public void queryRoleList() throws Exception{
    	dao.queryRoleList();
    }
}

Dao层:

//这个注解通常不用,后期dao使用mapper
@Repository("dao")
public class RoleDaoImpl implements RoleDao {
	private Integer userId ;
	private String userName;
	private String nikeName;
	public RoleDaoImpl() {
	}

	public RoleDaoImpl(Integer userId,String userName,String nikeName) {
		this.userId = userId;
		this.userName=userName;
		this.nikeName=nikeName;
	}
	
	public void queryRoleList() throws Exception {
		System.out.println("查询角色列表操作");
	}
	
	public void showUserId() throws Exception{
		System.out.println(this.userId);
	}
}

以后的service开发就可以只定义dao,自动注入,然后写业务逻辑。

猜你喜欢

转载自blog.csdn.net/AhaQianxun/article/details/93891157