Spring 注解之扫描组件

1、特定的组件包含:

      -@Component:基本注解,标识了一个受Spring管理的组件

      -@Repository:标识持久层组件

      -@Service:标识业务层组件

      -@Controler:标识表现层组件

       他们之间是可以混用的。

 

2、在bean的xml文件中配置扫描包路径

<?xml version="1.0" encoding="UTF-8"?>

<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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <!--   <bean id="helloWorld" class="spring.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>-->
   <context:component-scan base-package="spring.annotations"></context:component-scan>  


</beans>

3、创建controller类添加@Controller 注解

package spring.annotations.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import spring.annotations.service.UserService;

@Controller
public class UserController {
    @Autowired
     UserService userService;
     public void execute(){
         System.out.println("UserControler Executor");
         userService.add();
     }
}
 

4、创建service类,添加@Service 注解

package spring.annotations.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    
    public void add(){
        System.out.println("UserService add");
    }

}
5、创建repository类,添加Repository注解

package spring.annotations.repository;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepositoryImpl implements UserRepository {

    @Override
    public void save() {
         System.out.println("save user");
    }

}
 

6、编写测试类

 

package spring.annotations;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import spring.annotations.controller.UserController;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        ApplicationContext context = 
                         new ClassPathXmlApplicationContext("Beans.xml");
        TestObject obj = (TestObject) context.getBean("testObject");
        System.out.println(obj);
        
        UserController controler = (UserController) context.getBean("userController");
        
        controler.execute();
                
    }

}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值