您的位置:首页 > 编程语言 > Java开发

项目中使用的spring 注解说明

2015-06-13 11:53 393 查看
以前在项目中spring 的依赖注入使用 xml 配置,现在使用 注解(Annotation) 来实现配置。

1声明bean

1.1实例

有类:

public class MyBean{

//do something

}

xml 方式:

<bean id="myBean"class="com.bean.MyBean"/>

注解方式:

@Component("myBean")

public class MyBean {

//do something

}

1.2说明

除了使用 @Component 注解,还可以使用 @Controller, @Service, @Repository 。一般情况下 service 使用 @Service ,dao 使用 @Repository ,其他的使用 @Component(@Controller 一般在使用 spring mvc 的时候使用)。

1.2.1配置scope (生命周期)

spring 默认为 "singleton" 单例,没有特别原因建议使用"prototype"

xml 方式:

<bean id="myBean" class="com.bean.MyBean" scope="prototype"/>

注解方式:

@Component("myBean")

@Scope("prototype")

public class MyBean {

}

2.注入bean

2.1实例

将 myBean 注入到 myBean2

有类:

public class MyBean{

//do something

}

public class MyBean2 {

private MyBean myBean;

//do someting

}

xml 方式:

<bean id="myBean" class="com.bean.MyBean"/>

<bean id="myBean2"class="com.bean.MyBean2">

<propertyname="myBean" ref="myBean"/>

</bean>

注解方式:

@Component("myBean")

public class MyBean {

//do something

}

@Component("myBean2")

public class MyBean2 {

@Autowired

private MyBean myBean;

//do someting

}

2.2说明

注入bean 可以使用以下注解

@Resource, @Autowired, @Inject

2.2.1注入方式

a)属性注入

@Component

public class MyBean2 {

@ Autowired

private MyBeanmyBean;

}

b)方法注入

@Component

public class MyBean2 {

private MyBean myBean;

@ Autowired

private voidsetMyBean (MyBean myBean){

this.myBean = myBean;

}

}

c)构造方法注入

@Component

public class MyBean2 {

private MyBean myBean;

@ Autowired

public MyBean2(MyBean myBean){

this.myBean = myBean;

}

}

3.其他

依赖注入的层次最好符合这样的约束:action 使用 service ;service 使用 dao.

3.1注解使用示例

public interface UserDao {

}

//通过 @Compoent 声明 spring bean,@Repository

@Scope("prototype")

public class UserDaoImpl implements UserDao {

//省略...

}

/*************************性感的分隔线**************************/

public interface UserService {

}

@Service

@Scope("prototype")

public classUserServiceImpl implements UserService {

//通过 @Autowired 注解注入 SysUserLoginDao 依赖

@Autowired

private UserDao userDao;

//省略

}

public class UserAction {

@Autowired

privateUserService userService;

public Stringexecute(){

//do something

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: