如何在Spring Boot MVC Web应用程序中实现Bean注入

huangapple go评论76阅读模式
英文:

How to make bean injection in spring boot mvc web application

问题

以下是您要翻译的内容:

你能告诉我在哪里以及如何编写以下代码:

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);
    }
}

Products.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;
    }
    // ...
}

我的 beans.xml 文件

<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>
英文:

Can you please tell where and how i have to write:

final ApplicationContext context = new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);
final HelloController store = context.getBean(&quot;store&quot;, HelloController .class);

so that dependency injection takes place and my objects are created when the application starts. And i could get the total price of created objects.

HelloController.java

@Controller
public class HelloController {
private List&lt;Products&gt; storeList  = new ArrayList&lt;Products&gt;();
private int            totalPrice = 0;
public List&lt;Products&gt; getStoreList() {
return this.storeList;
}
public int getTotalPrice() {
return this.totalPrice;
}
@RequestMapping(&quot;/&quot;)
public String index() {
return &quot;index&quot;;
}
@PostMapping(&quot;/totalprice&quot;)
public String countTotalPrice(@RequestParam(&quot;name&quot;) final String name, final Model model) {
final String[] values = name.trim().split(&quot;\\s*,\\s*&quot;);
final List&lt;Integer&gt; listIds = new ArrayList&lt;Integer&gt;();
for (int i = 0; i &lt; values.length; i++) {
listIds.add(Integer.parseInt(values[i]));
for (int j = 0; j &lt; this.storeList.size(); j++) {
if (listIds.get(i) == this.storeList.get(j).getId()) {
this.totalPrice += this.storeList.get(j).getPrice();
}
}
}
model.addAttribute(&quot;name&quot;, this.totalPrice);
return &quot;totalprice&quot;;
}
public void setStoreList(final List&lt;Products&gt; storeList) {
this.storeList = storeList;
}
}

MainApp.java - Run the Application

@SpringBootApplication
public class MainApp {
public static void main(final String[] args) {
SpringApplication.run(MainApp.class, args);
}
}

Products.java - my class for products

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;
}
...

My beans.xml file

&lt;beans 
... 
&lt;bean id=&quot;product1&quot;
class=&quot;... .Products&quot;&gt;
&lt;constructor-arg name=&quot;name&quot; value=&quot;Cherry&quot; /&gt;
&lt;constructor-arg name=&quot;price&quot; value=&quot;500&quot; /&gt;
&lt;constructor-arg name=&quot;id&quot; value=&quot;1&quot; /&gt;
&lt;/bean&gt;
&lt;bean id=&quot;product2&quot;
class=&quot;... .Products&quot;&gt;
&lt;constructor-arg name=&quot;name&quot; value=&quot;Cucumber&quot; /&gt;
&lt;constructor-arg name=&quot;price&quot; value=&quot;1000&quot; /&gt;
&lt;constructor-arg name=&quot;id&quot; value=&quot;2&quot; /&gt;
&lt;/bean&gt;
&lt;bean id=&quot;product3&quot;
class=&quot;... .Products&quot;&gt;
&lt;constructor-arg name=&quot;name&quot; value=&quot;Apple&quot; /&gt;
&lt;constructor-arg name=&quot;price&quot; value=&quot;3000&quot; /&gt;
&lt;constructor-arg name=&quot;id&quot; value=&quot;3&quot; /&gt;
&lt;/bean&gt;
&lt;bean id=&quot;store&quot;
class=&quot;... .controller.HelloController&quot;&gt;
&lt;property name=&quot;storeList&quot;&gt;
&lt;list&gt;
&lt;ref bean=&quot;product1&quot;/&gt;
&lt;ref bean=&quot;product2&quot;/&gt;
&lt;ref bean=&quot;product3&quot;/&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;/beans&gt;

答案1

得分: 1

你可以创建配置:

@Configuration
@ImportResource({"classpath*:beans.xml"})
public class Config {
}

并且可以像这样从 XML 中使用你的 beans:

@Controller
public class HelloController {
    @Autowired
    Store store;
    ...
}
英文:

You can create configuration:

@Configuration
@ImportResource({&quot;classpath*:beans.xml&quot;})
public class Config {
}

And use your beans from xml like:

@Controller
public class HelloController {
@Autowired
Store store;
...

答案2

得分: 1

@ImportResource("classpath:beans.xml")

将这个注解添加到SpringBootApplication注解旁边

然后在需要引用 'store' bean 的地方只需这样写

@Autowired
Store store;
英文:
@ImportResource(&quot;classpath:beans.xml&quot;)

Add this annotation next to the SpringBootApplication annotation.

Then, where u need reference to the 'store' bean, just say

@Autowired
Store store;

huangapple
  • 本文由 发表于 2020年3月4日 04:28:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/60515015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定