Подскажите, пожалуйста, где и как мне написать:
final ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
final HelloController store = context.getBean("store", HelloController .class);
, чтобы произошло внедрение зависимости и мои объекты были созданы при запуске приложения. И я мог бы получить общую стоимость созданных объектов.
HelloController. java
@Controller
public class HelloController {
private List<Products> storeList = new ArrayList<Products>();
private int totalPrice = 0;
public List<Products> getStoreList() {
return this.storeList;
}
public int getTotalPrice() {
return this.totalPrice;
}
@RequestMapping("/")
public String index() {
return "index";
}
@PostMapping("/totalprice")
public String countTotalPrice(@RequestParam("name") final String name, final Model model) {
final String[] values = name.trim().split("\\s*,\\s*");
final List<Integer> listIds = new ArrayList<Integer>();
for (int i = 0; i < values.length; i++) {
listIds.add(Integer.parseInt(values[i]));
for (int j = 0; j < this.storeList.size(); j++) {
if (listIds.get(i) == this.storeList.get(j).getId()) {
this.totalPrice += this.storeList.get(j).getPrice();
}
}
}
model.addAttribute("name", this.totalPrice);
return "totalprice";
}
public void setStoreList(final List<Products> storeList) {
this.storeList = storeList;
}
}
MainApp. java - Запустить приложение
@SpringBootApplication
public class MainApp {
public static void main(final String[] args) {
SpringApplication.run(MainApp.class, args);
}
}
Продукты . java - мой класс для продуктов
public class Products {
private String name;
private int price;
private int id;
public Products(final String name, final int price, final int id) {
this.name = name;
this.price = price;
this.id = id;
}
...
Мои бобы. xml file
<beans
...
<bean id="product1"
class="... .Products">
<constructor-arg name="name" value="Cherry" />
<constructor-arg name="price" value="500" />
<constructor-arg name="id" value="1" />
</bean>
<bean id="product2"
class="... .Products">
<constructor-arg name="name" value="Cucumber" />
<constructor-arg name="price" value="1000" />
<constructor-arg name="id" value="2" />
</bean>
<bean id="product3"
class="... .Products">
<constructor-arg name="name" value="Apple" />
<constructor-arg name="price" value="3000" />
<constructor-arg name="id" value="3" />
</bean>
<bean id="store"
class="... .controller.HelloController">
<property name="storeList">
<list>
<ref bean="product1"/>
<ref bean="product2"/>
<ref bean="product3"/>
</list>
</property>
</bean>
</beans>