Spring Annotation-Based Development and MyBatis Integration Guide
This article explains how Spring 3.0's pure annotation development simplifies bean configuration, demonstrates defining beans with @Component, managing bean scopes, performing various injection techniques, reading properties files, and integrating MyBatis, providing complete code examples and best‑practice tips for backend Java developers.
Preface
Spring 3.0 introduced a pure annotation development mode, aiming to simplify development even further; the framework’s features shine when integrating with MyBatis.
Annotation Development
As explained by a senior mentor, an annotation is a special interface that extends Annotation; its concrete implementation is a runtime‑generated dynamic proxy class.
Annotations are essentially interfaces that inherit from Annotation , and their concrete implementation classes are dynamic proxy objects generated by the Java runtime.
When we retrieve an annotation via reflection, the returned object is a dynamic proxy such as $Proxy1. Invoking a custom annotation method on this proxy ultimately calls the AnnotationInvocationHandler 's invoke method, which looks up the value in the memberValues map. The memberValues map originates from the Java constant pool.
Defining Beans with Annotations
Before annotation development, beans were defined in XML like:
<bean id="a" class="yu7daily.Dao.Daoimpl.A" />With annotation development, the <bean> tag is removed and the class is annotated with @Component("a"):
@Component("a")
public class A implements AA {
public void save() {
System.out.println("book dao save ...");
}
}Scanning the package in XML registers the class in the IoC container:
<context:component-scan base-package="yu7daily.Dao"/>The component-scan tag means “component scan”; a broader package path scans more classes (slower), while a narrower path scans fewer classes (faster).
Finally, the bean can be obtained from the container:
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
A aa = (A) ctx.getBean("a");
aa.save();
}Note: Interfaces cannot be instantiated directly, so annotations should not be placed on interfaces.
Derived Annotations
Three annotations derived from @Component are:
@Controller
@Service
@RepositoryThey correspond to the MVC layers—presentation, service, and data—making it easy to distinguish class responsibilities.
Pure Annotation Development Mode
The pure‑annotation mode eliminates XML configuration entirely, using annotations such as: @Configuration: marks a class as a Spring configuration class. @ComponentScan: defines the package(s) to scan.
Example configuration class:
@Configuration
@ComponentScan("yu7daily")
public class Config { ... }Beans can then be retrieved with:
ApplicationContext acct = new AnnotationConfigApplicationContext(Config.class);This replaces the XML <context:component-scan .../> completely.
Configuring Bean Scope
Beans are singleton by default. To create a non‑singleton bean, use the @Scope annotation with the value "prototype":
@Component("a")
@Scope("prototype")
public class A implements AA {
public void save() {
System.out.println("hello~");
}
}Annotation‑Based Injection
Set injection works by calling a setter method inside the container. In pure‑annotation mode, field injection is achieved with @Autowired:
@Service
public class A implements AA {
@Autowired
private B b;
}Automatic wiring can be configured in XML with autowire="byType", but the annotation approach achieves the same result without explicit property tags.
1. Automatic Wiring
Automatic wiring uses reflection to create objects and set private fields (via “violent” reflection). The underlying mechanism remains unchanged.
2. Name‑Based Injection
If multiple beans of the same type exist, type‑based injection may fail with NoUniqueBeanDefinitionException. Use @Qualifier("beanName") together with @Autowired to specify the exact bean:
@Repository("b")
public class B implements BB {
@Autowired
@Qualifier("a")
private AA aa;
public void save() { aa.save(); }
} @Qualifiermust be used alongside @Autowired.
3. Simple Value Injection
Inject simple data (e.g., a String) with @Value:
@Repository("a")
public class A implements AA {
@Value("hello java")
private String str;
public void save() { System.out.println(str); }
}The primary purpose of @Value is to read values from configuration files.
4. Reading a properties File
Mark a configuration class with @PropertySource("test.properties") to specify the properties file, then inject values with @Value("${name}"):
@Configuration
@ComponentScan("yu7daily")
@PropertySource("test.properties")
public class SpringConfig { } @Repository("a")
public class A implements AA {
@Value("${name}")
private String str;
public void save() { System.out.println(str); }
}Running the program prints the property value (e.g., lanyangyang).
Spring Integration with MyBatis
After configuring MyBatis, Spring integration mainly manages SqlSessionFactory and scans Mapper interfaces.
1. Add Required JARs
<artifactId>spring-jdbc</artifactId>
<artifactId>mybatis-spring</artifactId>2. Configure DataSource
(Illustrated with an image in the original article.)
3. Create Main Configuration Class
@Configuration
@ComponentScan("yu7daily")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
public class SpringConfig { ... }4. Create MyBatis Configuration Class to Obtain SqlSessionFactory
(Illustrated with an image in the original article.)
5. Retrieve Beans in Main Method
ApplicationContext ACC = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService acc = ACC.getBean(AccountService.class);This approach dramatically reduces boilerplate compared with traditional XML configuration.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
