我有一个包含所有 @Service、@RestController、@Repository beans 的 Restful 应用程序。我 Autowiring 所需的 bean。
现在我想在另一个不受spring管理的类中使用@service类,这可能吗?
如果有任何差异,这 2 个类也位于 2 个不同的 Maven 项目中
我尝试创建一个新对象,正如预期的那样,没有成功。 我也尝试过创建不同的构造函数也没有成功。
我在谷歌上搜索了一些答案,但还没有找到,所以现在我向你们专家求助;)
我想使用的类!
@Service
public class ProductService {
ProductRepository repository;
@Autowired
public ProductService(ProductRepository repository){
this.repository = repository;
}
}
休息 Controller
@RestController
@RequestMapping(path = "/product")
public class ProductResource {
@Autowired
ProductService service;
}
repo 协议(protocol)
public interface ProductRepository extends JpaRepository<Product,Long> {
}
这是我要创建服务的位置。
public static void main(String[] args) {
String chromeDriver = args[0];
String method = args[1];
String domainName = args[2];
ProductService service = new ProductService();
System.setProperty("webdriver.chrome.driver", chromeDriver);
Runner runner = new Runner(method,domainName);
runner.run();
}
最佳答案
据我所知,只要 Spring 托管类(在本例中为服务)不包含任何 Spring 依赖项,您就可以在非 Spring 托管类中实例化 Spring 托管类,因为它们将保持为空(未初始化),因为它们永远不会被 Spring 注入(inject)。
您的服务对我来说看起来不错,因为 ProductRepository 字段不是 @autowired,但在您的代码中您正在创建这样的 ProductService:
ProductService service = new ProductService();
虽然 ProductService 类中不存在此无参数构造函数:
@Service
public class ProductService
{
ProductRepository repository;
@Autowired
public ProductService(ProductRepository repository)
{
this.repository = repository;
}
}
关于java - 创建@Service bean的对象,可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58198158/