在Spring开发体系中很少用到多例的Bean,所以这个知识点很容易被忘记。
Spring注入多例Bean的俩种方式:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class BeanTest {
@Bean
@Scope("prototype")
public StaffDTO staffDTO() {
return new StaffDTO();
}
}
1.使用ObjectFactory
示例:
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.test.entity.StaffDTO;
@RestController
@RequestMapping("/staffs")
public class StaffController {
@Autowired
private ObjectFactory<StaffDTO> objectFactory;
@GetMapping("/dto")
public Object getDto() {
return objectFactory.getObject();
}
}
2.使用@Lookup注解
示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.test.entity.StaffDTO;
@RestController
@RequestMapping("/staffs")
public abstract class StaffController {
@Lookup
protected abstract StaffDTO getStaffDTO();
@GetMapping("/dto")
public Object getDto() {
return getStaffDTO().toString();
}
}