Spring入门(7)-自动检测Bean

Spring入门(7)-自动检测Bean

本文介绍如何自动检测Bean。

0. 目录

  1. 使用component-scan自动扫描
  2. 为自动检测标注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

context:component-scan会自动检测如下注解:

  • @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();
}
}
上一篇:Jmeter在Linux下执行


下一篇:linq查询时查询语句中附带多个查询时“已有打开的与此 Command 相关联的 DataReader,必须首先将它关闭”