每天注解学习(六)声明/注入bean的注解

目录:

  • @Component
  • @Service
  • @Repository
  • @Mapper
  • @Controller
  • @Autowired
  • @Inject
  • @Resource

 

相关注解:

(1)@Component:组件,没有明确的角色

@Component
public class KafkaConsumer {

    private static final Logger log = LoggerFactory.getLogger(KafkaConsumer.class);

    @Autowired
    private UrlProperties urlProperties;

    @Autowired
    private ObjectMapper objectMapper;

    private ExecutorService executorService = Executors.newFixedThreadPool(4);
    private static final KafkaConsumer consumer = new KafkaConsumer();
    public synchronized static KafkaConsumer getInstance() { return consumer; }

    @KafkaListener(topics = {KafkaMessageConfig.BUSINESS_SERVICE_TOPIC})
    public void processMessage(ConsumerRecord<String, String> consumer) {
        try {
            String topic = "";
            String key = "";
            String message = "";
            String connectorId = "";
            String startChargeSeq = "";
            if (consumer.topic() != null) {
                topic = consumer.topic();
            }
            if (consumer.key() != null) {
                key = consumer.key();
            }
            if (consumer.value() != null) {
                message = consumer.value();
            }

            if (topic == null || "".equals(topic.trim()) || " ".equals(topic)) {
                log.warn("[processMessage] invalid topic {}", topic);
                return;
            }
            if (key == null || "".equals(key.trim()) || " ".equals(key)) {
                log.warn("[processMessage] invalid key {}", key);
                return;
            }
            if (!new JsonValidator().validate(message)) {
                log.warn("[processMessage] invalid message string {}", message);
                return;
            }

            Map<String, Object> body = JsonUtil.json2Bean(message, Map.class);
            Map<String, Object> params = new HashMap<>();
            if (body == null || body.isEmpty() || !body.containsKey("OperationType")) {
                log.warn("[processMessage] invalid message string {}", message);
                return;
            }

            String operationType = (String) body.get("OperationType");
            int protocolType = (int) body.get("ProtocolType");
            String protocolVersion = (String) body.get("ProtocolVersion");
            log.info("[Message] topic-->{}, key-->{}, message-->{}", topic, key, message);
           ......
}

(2)@Service:在业务逻辑层使用(service层)

@Slf4j
@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private RawUserMapper userMapper;

    @Autowired
    private UserGroupService userGroupService;

    @Override
    public User loadUserByUserId(int userId) throws ServerException {
        try {
            RawUser rawUser = userMapper.getById(userId);
            User user = refreshProperty(rawUser);
            if (user != null) {
                user.setUserGroups(userGroupService.loadUserGroupListByUserId(userId));
            }
            return user;
        } catch (Exception e) {
            throw new ServerException(e);
        }
    }
}

 

(3)@Repository/@Mapper:用于标注数据库访问层,也可以说被作为持久层操作(数据库)的bean来使用,即DAO组件.

理解:

@Repository(value="userDao")注解是告诉Spring,让Spring创建一个名字叫“userDao”的UserDaoImpl实例。
当Service需要使用Spring创建的名字叫“userDao”的UserDaoImpl实例时,就可以使用@Resource(name = "userDao")注解告诉Spring,Spring把创建好的userDao注入给Service即可。

比较:

  • 如果在接口上@Mapper,然后再在 xml中的namespace指向mapper,那么spring就能动态生成一个Mapper的bean,然后你在serviceImpl中的
 @Autowired

 pravate XXXMapper xxmapper;

       就会被这个bean注进去。

  • 如果在DaoImpl中加了@Repository,那么在spring的扫包机制下,也会生成这个dao的bean,注入你serviceImpl中的
 @Autowired

 private xxxDao   xxxdao;

代码:

@Mapper
public interface DeviceMapper {

    int getCountByDeviceNumber(String chargePointSerialNumber);

    void updateDevice(DeviceEntity deviceEntity);

    void updateStatusAndBindUserId(@Param("deviceNumber") String deviceNumber, @Param("status") String status, @Param("userId") Integer userId);

    void updateDeviceDetail(@Param("deviceNumber") String deviceNumber, @Param("deviceDetailStr") String deviceDetailStr);

    void updateStatus(@Param("deviceNumber") String deviceNumber, @Param("status") String status);

    String getStatus(@Param("deviceNumber") String deviceNumber);

    String findDeviceNumber(@Param("deviceNumber") String deviceNumber);

}

 

(4)@Controller:在展现层使用,控制器的声明(C),注解类进行前端请求的处理,转发,重定向。包括调用Service层的方法


@RequestMapping("/v1")
@Controller
@Slf4j
public class OcController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private HttpRequestHolder httpRequestHolder;
    @Autowired
    private OcConfig ocConfig;
    @Autowired
    private TransactionIdHelper transactionIdHelper;


    /**
     * 当充电器接收到 RemoteStartTransaction,充电器用户可以开始充电。
     * 已收到RemoteStartTransaction 后,立即启动会话。
     * 如果电动车未连接,则不会有回复消息。
     *
     * @param paramVo
     * @return
     */
    @HystrixCommand(fallbackMethod = "defaultRemoteStartTransaction")
    @RequestMapping(value = "/remoteStartTransaction", method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<ResponseVo> remoteStartTransaction(
            @RequestBody com.chargedot.ocppservice.controller.request.RemoteStartTransactionRequest paramVo) {
        log.info("[remoteStartTransaction][param]{}", paramVo);
        RemoteStartTransactionRspVo response = new RemoteStartTransactionRspVo();
//        ResponseVo response = new ResponseVo();
    ......
}

 

(5)@Autowired:由Spring提供,自动注入

(6)@Inject:由JSR-330提供

每次都要生成相应的set方法非常麻烦,现在如果我们使用javax.inject.jar,只需要在相应类的属性上面加上@Inject。

 

(7)@Resource:由JSR-250提供

  • @Resource默认按byName自动注入。
  • 既不指定name属性,也不指定type属性,则自动按byName方式进行查找。如果没有找到符合的bean,则回退为一个原始类型进行进行查找,如果找到就注入。
  • 只是指定了@Resource注解的name,则按name后的名字去bean元素里查找有与之相等的name属性的bean。
  • 只指定@Resource注解的type属性,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常。
     
public class PersonServiceBean implements PersonService {
    @Resource 
    private PersonDao personDao;

    private String name;

    public PersonServiceBean() {}

    public PersonServiceBean(PersonDao personDao, String name) {
        this.personDao = personDao;
        this.name = name;
    }

    @Override
    public void save() {
        // System.out.println(name);
        personDao.add();
    }
}

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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <context:annotation-config/>

    <bean id="personDao" class="cn.itcast.dao.impl.PersonDaoBean"></bean>
    <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
</beans>

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值