Spring入门之常用注解
参与代码编译,以@开头,类似与添加注释,又不是注释,它的作用是将类或方法与特定的应用程序相关联。
Spring使用annotation,spring使用一些特殊的annotation来标注bean类。
@Component:标准一个普通的spring Bean类。 @Controller:标注一个控制器组件类。 @Service:标注一个业务逻辑组件类。 @Repository:标注一个DAO组件类。
Bean实例的名称默认是Bean类的首字母小写,其他部分不变。
@Controller,@Service,@Repository会携带更多语义。尽量考虑使用@Controller,@Service,@Repository代替通用的@Component。
@Resource位于java.annotation包下,来自于java EE规范的一个annotation。
@Resource有一个name属性,在默认情况下,spring将这个值解释为需要被注入的Bean实例的名字。
@Scope:注解也可以指定Bean实例的作用域。
@PostConstruct和@PreDestory位于java.annotation包下。 在spring中用于定制spring容器中bean的生命周期行为。 @PostConstruct修饰的方法是bean的初始化之前的方法。 @PreDestory修饰的方法是bean销毁之前的方法。
先建一个普通bean,TestDao.java
再建一个java类,TestService.java
Bean配置文件,applicationContext.xml
执行程序test.java
public class test {
publicstatic void main( String[] args )
{
ApplicationContext context =
newClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
TestService ts =(TestService)context.getBean("testService");
System.out.println(ts);
ts.output();
}
}
程序目录
执行结果:
com.spring.lsh.demo.services.TestService@53f65459
this is testservice:com.spring.lsh.demo.dao.TestDao@3b088d51
TestDao.java
@Component(或者@Repository)
publicclass TestDao {
publicvoid output(){
System.out.println("this is output");
}
}
TestService.java
@Component(或者@Service)
publicclass TestService {
@Autowired
TestDao testdao;
publicvoid output(){
System.out.println("this is test service"+":"+testdao );
}
}
配置文件更改如图
输出结果:
com.spring.lsh.demo.services.TestService@52e677af
this is testservice:com.spring.lsh.demo.dao.TestDao@35083305
@Service("lsh")
publicclass TestService {
检索该bean
TestService ts = (TestService)context.getBean("lsh");
注:部分资料摘自易百
SpringMVC常用注解及实例后续介绍,请关注“IT测试前沿”