在前文中,标签@ComponentScan所注解的Java config类必须和待扫描类在同一个包中,但是更多的时候真正需要的是可以扫描指定的类。
本文记录解决的方案
问题、实现扫描指定的类
@ComponentScan有两个配置项 basePackages basePackageClasses
basePackages:可以配置一个java包的数组,spring会扫描对应的包及其子包。
basePackageClasses:可以配置多个类,Spring会根据类所在的包,为包和子包进行扫描装配对应配置的bean。
案例:
在service包下定义一个接口RoleService,里面定义函数pringRoleInfo参数为Role实例
package com.ssm.spring.annotation.service;
package com.ssm.spring.annotation.pojo.Role;
public interface RoleService {
public void printRoleInfo(Role role);
}
在impl包下定义类RoleServiceImpl实现该接口,其中@Component注解表明RoleServiceImpl是Spring所需要的bean。
package com.ssm.spring.annotation.service.impl;
import com.ssm.spring.annotation.pojo.Role;
import com.ssm.spring.annotation.service.RoleService;
import org.springframework.stereotype.Component;
@Component("roleService1")
public class RoleServiceImpl implements RoleService {
@Override
public void printRoleInfo(Role role) {
System.out.println("id ="+role.getId());
System.out.println("roleName ="+role.getRoleNames());
System.out.println("note ="+role.getNote());
}
}
Role的定义与前面一样,代码如下; @Component注解表明Role也是Spring需要的bean,即Role以及RoleServiceImpl都需要放入Ioc容器。
package com.ssm.spring.annotation.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component(value = "role") //类在spring中的id
public class Role {
@Value("1")
private Long id;
@Value("role_name_1")
private String roleNames;
@Value("role_note_1")
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleNames() {
return roleNames;
}
public void setRoleNames(String roleNames) {
this.roleNames = roleNames;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
最后一步定义java config类,config类上方使用@ComponentScan注解,同时配置basePackageClasses,分别加入Role.class以及RoleServiceImpl.class,这样Spring就会扫描这两个类所在的包以及子包装配对应配置的Bean。
如果使用basePackages,则注解改成
@Component(basePackages={"com.ssm.spring.annotation.pojo","com.ssm.spring.annotation.service.impl"}),分别为Role和RoleServiceImpl所在包的全限定名。
package com.ssm.spring.annotation.config;
import com.ssm.spring.annotation.pojo.Role;
import com.ssm.spring.annotation.service.impl.RoleServiceImpl;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackageClasses = {Role.class, RoleServiceImpl.class})
public class ApplicationConfig {
}
编写测试代码测试:
@Test
public void test(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
Role role = context.getBean(Role.class);
RoleService service = context.getBean(RoleService.class);
service.printRoleInfo(role);
}
注意事项:
如果采用多个@ComponentScan定义对应的一个包,每定义一个@ComponentScan就会生成一个实例,也就是说对应的Bean会生成多个实例。
如果在一个@ComponentScan中重复定义相同的包,不会造成多次扫描的问题,也就是说只生成一个Bean的实例。