Spring注解
配置文件如下:
<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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">
<context:annotation-config />
<context:component-scan base-package="Admin"/>
<context:component-scan base-package="Pub"/>
</beans>
spring会自动扫描Admin包和Pub包下的bean
在代码中添加注解:
@Controller, @Service, @Repository是@Component的细化,这三个注解比@Component带有更多的语义,
它们分别对应了控制层(action)、服务层(service)、持久层(dao)的类。
@Component泛指组件,当组件不好归类的时候我们可以使用这个注解进行标注,(现在可以都用此注解,可以只使用单一组件)
默认情况下,bean的名称是把类的名称第一个字母改为小写。
默认情况下,是bean是单例模式。
若要使用多例,则添加@Scope("prototype")即可
@Resource(name = "sessionFactory")
表示按名称注入
如DaoBasic.java:
@Repository
@Scope("prototype")
public class DaoBasic {
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@PostConstruct
public void postConstruct1(){//bean的构造函数
System.out.println("postConstruct1");
}
@PreDestroy
public void preDestroy1(){//bean的析够函数
System.out.println("preDestroy1");
}
}
@Repository表示添加一个DaoBasic类的bean名称为daoBasic。
若要修改名称为daoBasic1,可将@Repository修改为@Repository("daoBasic1")
@Scope("prototype")表示DaoBasic 类的bean是多例模式,
若要修改为单例模式,删除@Scope("prototype")即可。
@Resource(name = "sessionFactory")
表示将private SessionFactory sessionFactory;变量,注入一个名称为sessionFactory的bean
@PostConstruct 和 @PreDestroy
Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,您既可以通过实现 InitializingBean/DisposableBean 接口来定制初始化之后 / 销毁之前的操作方法,也可以通过 <bean> 元素的 init-method/destroy-method 属性指定初始化之后 / 销毁之前调用的操作方法。关于 Spring 的生命周期,笔者在《精通 Spring 2.x—企业应用开发精解》第 3 章进行了详细的描述,有兴趣的读者可以查阅。
JSR-250 为初始化之后/销毁之前方法的指定定义了两个注释类,分别是 @PostConstruct 和 @PreDestroy,这两个注释只能应用于方法上。标注了 @PostConstruct 注释的方法将在类实例化后调用,而标注了 @PreDestroy 的方法将在类销毁之前调用。
浙公网安备 33010602011771号