Spring自动扫描配置及使用方法

首先,检查一下你lib下有没有 common-annotations.jar 这个jar包 没有的话要导入工程。

下一步配置spring的配置文件applicationContex.xml,加入命名空间

红色为需要添加的内容

<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"
 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:component-scan base-package="你要扫描那个包(例如com.myprogram)" annotation-config="true"/>

这句话的意思时,当启动服务器的时候spring自动扫描你设置扫描的包下面的添加注解了的类

例如

服务层service定义接口和接口实现类

接口

public interface UsersLogsService {


 public abstract void delete(UsersLogs persistentInstance); 
}

实现类

@Service("UsersLogsService")//注解项
public class UsersLogsServiceImpl implements UsersLogsService {

 
     public void delete(UsersLogs persistentInstance) {
         
     }

}

控制层下的某个Action,

//自己定义需要注意的是"/loginAction"要与你的struts-config.xml配置文件中映射action的path一致

@Controller("/loginAction")//注解项
public class LoginAction extends DispatchAction {

//通过Resource注解我们就可以获得刚才注解了的UsersLogsService实例调用他的方法

@Resource(name="UsersLogsService") private UsersLogsService usersLogsService;

public ActionForward checkLogin(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {

          return null;

   }

}

到此位置,配置的流程就是这样,Dao数据操作层我没有写,创建Dao添加注解

服务层调用Dao就像上面控制层调用服务层一样,只要上面流程弄明白了,那么恭喜你,spring自动扫描的技术你也就学会了。

你可能感兴趣的:(java,spring,spring注解,Annotations,spring自动扫描)