在Spring中,手动注入Bean可以通过以下几种方式实现:
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
@Service
public class MyService {
@Autowired
private MyBean myBean;
}
<bean id="myBean" class="com.example.MyBean" />
<bean id="myService" class="com.example.MyService">
<property name="myBean" ref="myBean" />
</bean>
@Component
public class MyBean {
// ...
}
@Service
public class MyService {
@Autowired
private MyBean myBean;
}
@Service
public class MyService {
@Autowired
private MyBean myBean;
}
无论使用哪种方式,Spring都会在启动时自动扫描和处理Bean的注入。