Springmvc3.0 注解详解


Springmvc3.0 注解详解

1,  为什么要用注解,注解有什么好处?

Springmvc3.0 是基于注解进行编程,能大大提高开发效率,和维护成本。相比较SSH(struts2+spring+hibernate)   springmvc3.0去除了struts2.0 ,spring, hinernate 配置文件的编写和维护,从而可以更加快速的进行开发。所有这一切的实现就是基于注解进行编程。

 

2,  怎么去理解注解?

注解可以写在类上面,也可以写在方法上面,在目前我们的系统中,基于方法的注解主要用在控制器中,基于类的注解主要在控制器类, 业务逻辑层(serviceImpl), 数据层的(daoImpl)的实现类。

基于类的注解,例如controller , 相当于在系统中调用一个单例对象。

SpringControllerSingleton的。这就意味着会被多个请求线程共享

3,常用的注解有哪些?

• @Controller

• @Service

• @Autowired

• @RequestMapping

• @RequestParam

• @ModelAttribute

• @Cacheable

• @CacheFlush

• @Resource

• @PostConstruct

• @PreDestroy

• @Repository

• @Component (不推荐使用)

• @Scope

• @SessionAttributes

• @InitBinder

• @Required

• @Qualifier

在我们系统中需要理解的注解有哪些?以下做了一下分类,进行讲解:

在控制器中:

@Controller  -> 基于类的注解

例如

@Controller
public class SoftCreateController extends SimpleBaseController {}

或者
@Controller("softCreateController")

说明

@Controller 负责注册一个bean spring 上下文中,bean ID 默认为类名称开头字母小写

@Resource

例如

@Resource
private DataSource dataSource; // inject the bean named 'dataSource'

或者

@Resource(name="dataSource")
@Resource(type=DataSource.class)

说明

@Resource 默认按bean name 进行查找,如果没有找到会按type 进行在没有为 @Resource 注解显式指定 name 属性的前提下,如果将其标注在 BeanFactory 类型、ApplicationContext 类型、ResourceLoader 类型、ApplicationEventPublisher 类型、MessageSource 类型上,那么 Spring 会自动注入这些实现类的实例,不需要额外的操作。此时 name 属性不需要指定 ( 或者指定为""),否则注入失败;

-----------------------------------------------------------

@Service  基于业务逻辑层的注解

例如

@Service
public class SoftCreateServiceImpl implements ISoftCreateService {}

或者
@Service("tourSearchDataService")

publicclass TourSearchDataServiceImpl implements TourSearchDataService{}

说明

@Service 负责注册一个bean spring 上下文中,bean ID 默认为类名称开头字母小写

 

@Repository  基于数据层的注解

@Controller @Service 类似,都是向spring 上下文中注册bean ,不在赘述。

@Repository("tourSearchDataDao")

publicclass TourSearchDataDaoImpl extends SearchHibernateDaoSupport implements TourSearchDataDao {}

 

 

 

 

 

 

 

 

 

猜你喜欢

转载自dasheny.iteye.com/blog/2174913