Spring入门(7)-自动检测Bean
本文介绍如何自动检测Bean。
0. 目录
- 使用component-scan自动扫描
- 为自动检测标注Bean
1. 使用component-scan自动扫描
<?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"
>
<context:annotation-config/>
<context:component-scan base-package="com.chzhao.springtest"/>
</beans>
注:<context:annotation-config/>也可以去掉
package com.chzhao.springtest;
public interface IPersonBll {
void show();
}
package com.chzhao.springtest;
import org.springframework.stereotype.Service;
@Service
public class PersonBll implements IPersonBll {
public void show() {
System.out.println("show message");
}
}
package com.chzhao.springtest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class App {
@Autowired
private IPersonBll personBll;
public IPersonBll getPersonBll() {
return personBll;
}
public void setPersonBll(IPersonBll personBll) {
this.personBll = personBll;
}
public void showMsg() {
this.personBll.show();
}
}
package com.chzhao.springtest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext act = new ClassPathXmlApplicationContext(
"applicationContext.xml");
App a = (App) act.getBean(App.class);
a.showMsg();
}
}
2. 为自动检测标注Bean
会自动检测如下注解:
- @Component:通用的构造型注解,标识该类为Spring组件
- @Controller:标识该类为Spring MVC controller
- @Repository:标识该类为数据仓库
- @Service:标识此类定义为服务
@Component可以标注任意自定义注解,同时也可以命名Bean的ID。
package com.chzhao.springtest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("app1")
public class App {
@Autowired
private IPersonBll personBll;
public IPersonBll getPersonBll() {
return personBll;
}
public void setPersonBll(IPersonBll personBll) {
this.personBll = personBll;
}
public void showMsg() {
this.personBll.show();
}
}
package com.chzhao.springtest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext act = new ClassPathXmlApplicationContext(
"applicationContext.xml");
App a = (App) act.getBean("app1");
a.showMsg();
}
}