使用內置服務器啓動springboot
項目時,會從@SpringBootApplication
修飾類所在的包開始,加載當前包和所有子包下的類,將由@Component
@Repository
@Service
@Controller
修飾的類交由spring
進行管理。
package com.facade;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
String[] profiles = context.getEnvironment().getActiveProfiles();
if (profiles != null) {
for (String profile : profiles) {
System.out.println("------------start with profile : " + profile);
}
}
}
}
在使用Spring data jpa
時,通常都是繼承Repository
接口相關的其他接口,然後Spring data jpa
在項目啓動時,會爲所有繼承了Repository
的接口(@NoRepositoryBean
修飾除外)創建實現類,並交由Spring
管理。例如,
package com.facade.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.facade.entity.HttpDoc;
public interface HttpDocRepository extends PagingAndSortingRepository<HttpDoc, Long> {
}
package com.facade.service;
import com.facade.entity.HttpDoc;
public interface HttpDocService {
public HttpDoc save(HttpDoc entity);
public HttpDoc getById(Long id);
public Iterable<HttpDoc> findAll();
}
package com.
facade.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.facade.entity.HttpDoc;
import com.facade.repository.HttpDocRepository;
import com.facade.service.HttpDocService;
@Service
@Transactional
public class HttpDocServiceImpl implements HttpDocService {
@Autowired
private HttpDocRepository httpDocRepository;
@Override
public HttpDoc save(HttpDoc entity) {
return httpDocRepository.save(entity);
}
@Override
public HttpDoc getById(Long id) {
return httpDocRepository.findOne(id);
}
@Override
public Iterable<HttpDoc> findAll() {
return httpDocRepository.findAll();
}
}
以上代碼Application
處於HttpDocRepository
HttpDocServiceImpl
的根目錄中,所以HttpDocRepository
是可以被成功注入到HttpDocServiceImpl
中的。
如果將Application移動到其他平行目錄或者子目錄,就算使用scanBasePackages指定掃描目錄也無法將HttpDocRepository
成功注入,會產生如下錯誤描述
Action:
Consider defining a bean of type 'com.facade.repository.HttpDocRepository' in your configuration.