1.如果要项目中使用spring要先导入spring相关基本的jar包 主要有:
commons-logging-1.1.3.jar 日志管理spring-beans-3.2.5.RELEASE.jar bean节点spring-context-3.2.5.RELEASE.jar spring上下文节点spring-core-3.2.5.RELEASE.jar spring核心功能pring-expression-3.2.5.RELEASE.jar spring表达式相关表 maven需要配置pom.xml声明库 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yiibai</groupId> <artifactId>HelloSpring</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- Spring Core --> <!-- http://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- Spring Context --> <!-- http://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.4.RELEASE</version> </dependency> </dependencies> </project>2.实现具体的操作的一系列类 --如User类
3.然后进行xml配置,设置约束,一般为:applicationContext.xml或者bean.xml。 若为配置文件方式创建要在文件中写便签,指明需要实例化的类。以及对应的单利方式scope,是否懒加载lazy-init,set方法属性注入property,自动注入autowire等。
beans约束 <?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"> <!--IOC容器的配置,要创建的所有的对象都在这里配置--> <bean id="user" class="a_hello.User" autowire="byName"></bean> <!--具体的需要实例化的类--> </beans>如果是注解方式注入还要加上 context约束,并在对应的具体实现类上加上@component,单利/非单利,属性注入@Resource等。然后在配置文件中定义自动扫描<context:component-scan base-package="包"/> 自动装配 @autowired<context:annotation-config />,然后通过@Qualifier(“id”)注解我们用来控制bean应在字段上自动装配
AspectJ的注解 类似于代理。配置<aop:aspectj-autoproxy /> @Before – 方法执行前运行 @After – 运行在方法返回结果后 @AfterReturning – 运行在方法返回一个结果后,在拦截器返回结果 @AfterThrowing – 运行方法在抛出异常后 @Around – 围绕方法执行运行,结合以上这三个通知。及之前,又之后
4.完成action类 主要完成的就是text功能
@Test public void testAc() throws Exception{ //得到IOC容器对象 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //xml为之前配置的xml //从容器中获取bean User user = (User) ac.getBean("user"); //获取new出来的实例化对象