使用内置服务器启动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.