【Spring入门系列】注解方式配置IOC、DI

注解@Component

第一步:在applicationContext.xml 引入名称空间

第二步:在 applicationContext.xml 文件中引入注解扫描器

<!-- 组件扫描,扫描含有注解的类 -->
<context:component-scan base-package="com.ysdrzp.annotation"></context:component-scan>

第三步:添加注解

 1 @Component
 2 public class User {
 3 
 4     private int id;
 5 
 6     private String name;
 7 
 8     public int getId() {
 9         return id;
10     }
11 
12     public void setId(int id) {
13         this.id = id;
14     }
15 
16     public String getName() {
17         return name;
18     }
19 
20     public void setName(String name) {
21         this.name = name;
22     }
23 
24 }

第四步:测试

 1 public class TestAnnotation {
 2 
 3     @Test
 4     public void testAnnotation(){
 5         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 6         User user = (User) context.getBean("user");
 7         System.out.println(user.getName());
 8     }
 9 
10 }

如果其value属性的值为"",@Component等价于<bean id="user" class="com.ysdrzp.annotation.User"></bean>

如果其value属性值不为"",@Component("u")等价于<bean id="u" class="com.ysdrzp.annotation.User"></bean>

注解@Repository    @Service   @Controller

这三个注解都是针对 @Component 的衍生注解,它们的作用及属性都是一模一样的,只不过是提供了更加明确的语义化。

@Controller:一般用于表现层的注解。

@Service:一般用于业务层的注解。

@Repository:一般用于持久层的注解

注解@Resource

猜你喜欢

转载自www.cnblogs.com/ysdrzp/p/9925894.html
今日推荐