@Bean
注解:用来将该方法的返回值交给 springboot 管理,在工厂中默认标识:类名首字母小写。
编写对象
package com.rennen.configs;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Calendar;
@Configuration
public class BeanConfigs {
@Bean // 用来将该方法的返回值交给 springboot 处理
// @Scope(”prototype”)
public Calendar getCalendar() {
return Calendar.getInstance();
}
}
注入对象
package com.rennen.controller;
import com.rennen.entity.User;
import com.rennen.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Calendar;
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private User user;
@Autowired
private UserService userService;
@Autowired
private Calendar calendar;
@GetMapping("/hello2")
public String hello() {
System.out.println("hello springboot!!!");
System.out.println(user);
userService.save("Rennen");
System.out.println(calendar.getTime());
return "hello~~~";
}
}
<aside>
💡 这种方式创建的对象是单例的,如果想改为多例,可以加一个 @Scope(”prototype”)
注解。(默认的值为 singleton
)
</aside>