非Web项目:直接加载Spring内容需要借助ClassPathXmlApplicationContext
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml"); context.start();
Web项目:因为Tomcat等容器会加载web.xml的内容,所以在web.xml中配置如下内容即可:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
Spring最主要的配置则是application.xml,本文暂时只分析注解配置。
【application.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" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> </beans>
【自动加载】
<context:component-scan base-package="com.test.action"/> <!-- 加载单个 -->
<context:component-scan base-package="com.test.action,com.test.service,com.test.impl"/> <!-- 加载多个 -->
【注解类型】
@Component 是管理组件的通用形式,添加此注解表示把类交给Spring管理。在Spring 2.5中,提供了额外几个注解,分别是:@Repository(数据访问层Dao等)、@Service(业务层Service)、@Controller(控制层、Web层),此处用途是区分不同层次结构,应对将来Spring对应不同层次的特殊功能和优化。
@Controller 对应控制层Bean,也就是Action。此处相当于LoginAction将自己(默认为"LoginAction"或者通过value="xxx"来取新名字)交给Spring管理,之后只需要通过这个名字就可以把托管的Bean找出来用。
//@Controller(value="defineLoginAction") 自定义名字 @Controller @Scope("prototype") public class LoginAction extends ActionSupport { ... }
@Service 对应业务层的Bean,原理如上。
@Service("loginService") public class LoginService { ... }
@Repository 对应数据访问层Bean。
@Repository(value="userDao") public class UserDaoImpl implements UserDao{ ...... }
@Resource 用于装配Bean(提取托管到Spring的Bean),默认按名称进行装配,放在字段或者setter方法上并且没指定name时,按照字段或者属性名进行装配,。当找不到相同名字匹配时候,才按类型装配。
@Resource(name = "loginService") private LoginService loginService;
=(等价于)
LoginService loginService = new LoginService();
@Autowired 功能和@Resource相同,默认按类型装配,而且要求依赖对象必须存在,如果允许为null,要设置required属性为false,如:@Autowired(required=false),如果想使用名称装配可以结合@Qualifier注解进行使用,如下:
@Autowired() @Qualifier("userDao") private UserDao userDao;