多语言展示
当前在线:1225今日阅读:39今日分享:10

Spring中怎样实现自动扫描

最近小编收到很多问题,其中一个就是下面小编为大家整理一下关于Spring中怎样实现自动扫描的步骤,希望这些方法能够帮助到大家。
方法/步骤
1

首先 ,在Spring中单独给一个类装配,[html] view plain copy  。

2

然后,只需要在xml中配置bean即可,但是如果我们有一大推类要配置,那么一个一个配置就太麻烦了,这个时候用Spring中的自动扫描组件就很方便了。

3

然后,共有4种类型的自动扫描:@Component(任意组件)、@Repository(DAO层组件)、@Service(业务层组件)和@Controller(控制层组件)。

4

然后,将Spring的配置文件改为:    

5

然后,然后使用@Service注解标注PersonServiceBean类,如下:@Servicepublic class PersonServiceBean implements PersonService {    private PersonDao personDao;    public void setPersonDao(PersonDao personDao) {        this.personDao = personDao;    }    @Override    public void save() {        personDao.add();    } }。

6

最后,修改SpringTest类的代码为:public class SpringTest {    @Test    public void instanceSpring() {        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext('beans.xml');        PersonService personService = (PersonService) ctx.getBean('personServiceBean');        PersonDao personDao = (PersonDao) ctx.getBean('personDaoBean');        System.out.println(personService);        System.out.println(personDao);        ctx.close();    } }。

注意事项

上述方法为小编整理所得,希望能够帮助到大家。

推荐信息