使用spring框架
spring框架目前为市面上较为流行的一款全能型框架,它依赖ioc(控制反转)
和aop(面向切面编程思想)来进行实现
准备步骤:
一:
最少jar包:
spring-beans-.jar
spring-context-.jar
spring-core-.jar
spring-expression-.jar
spring-aop-.jar(4.0以上)
commons-logging-.jar(apache struts)
配置xml(Eclipse自动生成Spring配置文件需要安装Spring Tools插件)
控制反转IOC:Inversion of control 控制对象产生的权利反转到spring ioc
依赖注入DI:Dependency injection 依赖spring ioc注入对象
Spring注入:
set注入
p注入
构造注入
bean生命周期:(只适用于singleton;prototype的生命周期容器不能控制也就是不执行销毁)
lazy-init(也分局部和全局)
init-method=“方法名”、destroy-method=“方法名”
要使destroy-method执行使用:ApplicationContext接口的实现类
AbstractApplicationContext ctx = …
ctx.destroy();|ctx.close();
集合注入:查文档collections
List、Set、Map、Properties
annotation:(4.0以上依赖aop包)
1、配置xml的context头
<context:annotation-config/>(可选,被componet-scan集成)
<context:component-scan base-package="com.cssl"/>(必须有)
2、@Autowired默认是byType,如果找到多个类型匹配的,则按byName进行注入,如果还找不到对应bean,则报异常
3、多个类型在set方法上或者方法的参数前加 @Qualifier(“id的名称”)
4、@Resource(name=“udao”) 默认是byName,没有则按byType,byType又有多个则异常
name属性解析为bean的名字,而type属性则解析为bean的类型
@Resource(name=“usersDao”,type=UsersDaoImpl.class)
5、@Component, @Repository, @Service, @Controller效果一样,默认id为类名首字母小写
6、@PostConstruct(相当init-method) and @PreDestroy(相当destroy-method)
7、@Scope(“prototype”)
8、@Value("")注入固定值
注解可以不写set方法直接写到属性上annotation:(4.0以上依赖aop包)
1、配置xml的context头
<context:annotation-config/>(可选,被componet-scan集成)
<context:component-scan base-package="com.cssl"/>(必须有)
2、@Autowired默认是byType,如果找到多个类型匹配的,则按byName进行注入,如果还找不到对应bean,则报异常
3、多个类型在set方法上或者方法的参数前加 @Qualifier(“id的名称”)
4、@Resource(name=“udao”) 默认是byName,没有则按byType,byType又有多个则异常
name属性解析为bean的名字,而type属性则解析为bean的类型
@Resource(name=“usersDao”,type=UsersDaoImpl.class)
5、@Component, @Repository, @Service, @Controller效果一样,默认id为类名首字母小写
6、@PostConstruct(相当init-method) and @PreDestroy(相当destroy-method)
7、@Scope(“prototype”)
8、@Value("")注入固定值
注解可以不写set方法直接写到属性上