3.8毕设
在我们实际开发中,大量的使用自动配置。自动化配置既可以通过Java配置来实现,也可以通过xml配置来实现。
例如我有一个UserService,我希望在自动化扫描时,这个类能够自动注册到Spring容器中去,那么可以给该类添加一个@Service,.作为一个标记。
和@Service注解功能类似的注解,一共有四个:
@Component 在其他组件上添加注解时,使用@Component
@Repository 在Dao层,添加注解时,使用@Repository
@Service 在Service层上,添加注解时,使用@Service
@Controller 在Controller层,添加注解时,使用@Controller
这四个中,另外三个都是基于@Component做出来的
Java代码配置自动扫描

然后,在项目启动中加载配置类,在配置类中,通过@ComponentScan注解指定要扫描的包(如果不指定,默认情况下扫描的是配置类所在的包下载的Bean以及配置类所在的包下的子包下的类),然后就可以获取UserService的实例了。
XML配置自动化扫描
<context:component-scan base-package="org.javaboy.javaconfig"/>
上面这行配置表示扫描org.javaboy.javaconfig下的所有Bean。当然也可以按
照类来扫描。
XML配置完成后,在Jva代码中加载ML配置即可。
public class XMLTest
public static void main(String[]args){
ClassPathXmlApplicationContext ctx new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService ctx.getBean(UserService.class);
List<String>list userService.getAllUser();
System.out.println(list);
也可以在L配置中按照注解的类型进行扫描:
<context:component-scan base-package="org.javaboy.javaconfig"use-default-filters="true">
<context:exclude-filter type="annotation"expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
浙公网安备 33010602011771号