在Spring框架中,Bean 是一个核心概念,理解它对于掌握Spring至关重要。以下是Bean的详细解释:
@Component
、@Service
、@Repository
、@Controller
等注解。@PostConstruct
或init-method
)。@PreDestroy
或destroy-method
)。@Autowired
注解直接注入字段(不推荐)。@Autowired
或@Resource
注解实现。@Lazy
注解或lazy-init
属性配置。parent
属性指定。@Service
public class MyService {
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
public void doSomething() {
myRepository.save();
}
}
@Repository
public class MyRepository {
public void save() {
// 保存数据
}
}
本文系作者在时代Java发表,未经许可,不得转载。
如有侵权,请联系nowjava@qq.com删除。