Scan annotator in Spring

Keywords: Spring xml encoding

Scan annotator in Spring

1. Configure xml file

The code is as follows:

<?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.2.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    <!-- Classes annotated in scan package -->
    base-package="Packages to scan"
    <context:component-scan base-package="com.bdqn.dao,com.bdqn.service,com.bdqn.entity" />
</beans>

2. Write an annotation @ Repository("custom alias") in the implementation class of dao

The code is as follows:

package com.bdqn.dao.impl;

import org.springframework.stereotype.Repository;

import com.bdqn.dao.UserDao;
@Repository("Custom alias")
public class UserDaoImpl implements UserDao{

    @Override
    public int add() {
        System.out.println("Added successfully!");
        return 1;
    }
}

3. Add the annotation @ Service("custom alias") to the service implementation class

The code is as follows:

package com.bdqn.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.bdqn.dao.UserDao;
import com.bdqn.service.UserService;
@Service("Custom alias")
public class UserServiceImpl implements UserService{}

4. Add annotation to the method in the service implementation class

@Autowired: automatic assembly;
@Qualifier (custom alias): find the custom alias of the assembly object – associate the custom alias in the dao implementation layer.

5. Test code:

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); 
        UserService impl=(UserService) applicationContext.getBean("userService");---userService by@Service("Custom alias")Custom alias in
        impl.add();

Posted by SecureMind on Thu, 30 Apr 2020 21:05:38 -0700