Spring可以自动搜索Java路径下的Java类,并将其注册成bean实例;
需要使用注解来标记bean类;
@Component:标注一个普通的Spring Bean类
@Controller :标注一个控制器组件
@Service:标注一个业务逻辑组件类
@Repository:标注一个DAO组件类
@Scope:范围
@Scope(“singleton”)为默认 当两个对象一致时,为一个地址
@Scope(“prototype”),即使声明的对象一致,地址也不同
@Autowired :标注自动装配
public interface Axe {
public void clip();
}
@Component("my")
public class SteelAxe implements Axe {
public void clip() {
System.out.println("SteelAxe");
}
}
@Component
public class People {
@Autowired
@Qualifier("my")
private Axe axe;
public void go(){
this.axe.clip();
}
}
public class Test {
public static void main(String[] args) {
ApplicationContext cxt=new ClassPathXmlApplicationContext("bean1.xml");
People people= cxt.getBean("people",People.class);
SteelAxe steelAxe= cxt.getBean("my",SteelAxe.class);
StoneAxe stoneAxe= cxt.getBean("stoneAxe",StoneAxe.class);
people.go();
}
}
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
">
<context:component-scan base-package="com.helan.c"></context:component-scan>
</beans>
本文介绍Spring框架如何通过组件扫描自动注册Java类为bean实例,使用@Controller、@Service、@Repository和@Component注解标记不同类型的组件。同时,探讨了@Autowired和@Qualifier注解在依赖注入中的应用。
27万+

被折叠的 条评论
为什么被折叠?



